C++中返回值为 类对象 详解
代码如下:
#include <iostream>
using namespace std;
//建一个Test类
class Test
{
public:
Test()
{
a = 0;
b = 0;
cout << "无参构造函数被调用了" << endl;
}
Test(int aa, int bb)
{
a = aa;
b = bb;
cout << "有参构造函数被调用了" << endl;
}
Test(const Test& t)
{
a = t.a;
b = t.b;
cout << "复制构造函数被调用了" << endl;
}
void print()
{
cout << "a:" << a << endl << "b:" << b << endl;
}
~Test()
{
cout << "析构函数被调用了" << endl;
}
private:
int a;
int b;
};
//以下为几个方便说明的操作函数
Test g()
{
Test tt(11, 22);
return tt;
}
void play1()
{
g();
}
void play2()
{
Test t1 = g();
t1.print();
}
void play3()
{
Test t2(3, 4);
t2.print();
t2 = g();
t2.print();
}
//主函数
int main()
{
play2();
system("pause");
}
运行效果
调用此句时,g()调用部分与上例相似,不同的是g()传回来的参数给t1这个对象初始化,编译器在处理这句话时并没有创建一个新的对象来接受g()返回来的匿名对象的值,而是采取了优化,直接将这个匿名对象扶正,给其一个名字叫t1,所以匿名对象没有析构,随后可以打印t1(),当play2()函数结束时,才会将t1析构掉
参考:
https://blog.youkuaiyun.com/somehow1002/article/details/50206589
区别是深拷贝需要通过拷贝构造函数实现,浅拷贝 不需要。