#include <iostream>
using namespace std;
class A
{
public:
A();
A(const A&);
~A();
void operator = (const A&);
};
A::A() {cout<<"default constructor called\n";}
A::A(const A&){cout<<"copy constructor called\n";}
A::~A(){cout<<"destructor called\n";}
void A::operator = (const A&right_side){cout<<"assignment operator called\n";}
A foo( A& anObj)
{
cout<<"inside foo\n";
return anObj;
}
int main()
{
A thing;
A another = foo(thing);
system("pause");
return 0;
}
如果将foo 去掉&。变成
A foo( A anObj)
{
cout<<"inside foo\n";
return anObj;
}
3 回答

千巷猫影
TA贡献1557条经验 获得超7个赞
析构函数是在对象销毁的时候被系统调用的。
另外,你这里说反了,如果去掉foo里面去掉&,就会多生成一个临时变量,foo结束后,这个对象会被析构,这时候就会多输入一个destructor。如果是原来的A foo(A& anObj)这里的参数是引用,则不会创建一个对象,也就没有所谓析构。所以引用不会多一个destructor
其实main里面里面也有定义两个A对象,在退出main的时候,也会被调用的,你在命令行里运行程序可以看到,程序结束后会有两个destructor输出:
default constructor called inside foo copy constructor called destructor called // main函数里的A析构 destructor called // main函数里的A析构 Press any key to continue |
这是我在VC中运行的结果。

森栏
TA贡献1549条经验 获得超5个赞
在该类生成的对象实例声明周期结束时,才被调用
析构函数,在定义类时,进行声明、定义,主要用来释放申请的资源,
如定义了指针变量,并对其进行空间分配( new XX ),就可以在析构函数中
释放资源。举例入下
class A
{
Class B pt ;
A()
{
pt = new B();
}
~A()
{
if( NULL != pt)
{
delete pt ;
pt = NULL;
}
}
}// end of class A
- 3 回答
- 0 关注
- 9 浏览
添加回答
举报
0/150
提交
取消