自己写的一个有关构造函数和析构函数的测试程序,大家看下能不能写出运行结果
#include <iostream>
using namespace std;
class Obj
{
public:
Obj()
{
cout < < "Obj constructor is called! " < <endl;
}
Obj(const Obj& o)
{
cout < < "Obj copy constructor is called! " < <endl;
}
~Obj()
{
cout < < "Obj destructor is called! " < <endl;
}
};
Obj f(Obj o)
{
return o;
}
int main()
{
Obj o1;
Obj o2;
o2=f(o1);
//把上面两句改成下面一句,再猜下结果怎样。
//Obj o2=f(o1);
return 0;
}
//麻烦大家也写下每个输出结果是由哪个对象构造或析构引起的。
[解决办法]
Obj f(Obj o)
{
return o;
}
这里又构造了一个Obj
换成
Obj f(Obj& o)
{
return o;
}
就ok了
[解决办法]
f(o1) 在函数内部生成对象的副本
返回时,还要生成对象的副本
o2=f(o1);调用赋值函数
Obj o2=f(o1);调用拷贝构造函数
[解决办法]
1。 o1 被创建
o1: Obj constructor is called!
2。 o2 被创建
o2: Obj constructor is called!
3. f调用是o从o1拷贝构造
Obj copy constructor is called! "
4. 两个对象析构
Obj destructor is called! "
Obj destructor is called! "
[解决办法]
至于修改后的,则改变微
1。 o1 被创建
o1: Obj constructor is called!
2. f调用是o从o1拷贝构造
Obj copy constructor is called! "
3. o2=f(o1)返回,导致o2被拷贝构造
Obj copy constructor is called! "
4. 两个对象析构
Obj destructor is called! "
Obj destructor is called! "
[解决办法]
改动前
创建o1 调用构造函数
创建o2 调用构造函数
f(o1); -> o1传值做参数,调用拷贝构造函数
返回时生成返回值的副本,调用拷贝构造函数。
改动后:
创建o1 调用构造函数
f(o1); -> o1传值做参数,调用拷贝构造函数
返回时生成返回值的副本,调用拷贝构造函数。
你可以在写个赋值构造函数来观察