C++中返回值为 类对象 详解

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.csdn.net/somehow1002/article/details/50206589

区别是深拷贝需要通过拷贝构造函数实现,浅拷贝 不需要。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值