c++中临时对象的理解

目录

代码源码:

代码的执行结果:

下面对输出结果逐一分析: 


 

代码源码:

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
//#pragma warning(disable:4996)
using namespace std;

class test{
private:
	int i;
public:
	test(int k) :i(k){
		cout << "test(k) is called. i = " << i << endl;
	}
	~test(void){
		cout << "~test is called" << endl;
	}
	test(const test &para){
		i = para.i;
		cout << "test(const test &para) is called. i = " << i << endl;
	}
};

test play(test b)
{
	return b;
}
int main(int argc, char *argv[])
{
	test a = play(24);//调用带参数的构造函数,在play中生成临时对象
	cout << "************************************" << endl;
	test b = play(a);
	cout << "************************************" << endl;
	test c = play(10);
	cout << "************************************" << endl;
	test d = play(20);
	cout << "************************************" << endl;
	system("pause");
	return 0;
}

代码的执行结果:

下面对输出结果逐一分析: 

test(k) is called. i = 24//调用带参数的构造函数,在play中生成临时对象
test(const test &para) is called. i = 24//调用复制构造函数,把临时对象复制到a
~test is called//play中的临时对象析构
************************************
test(const test &para) is called. i = 24//调用复制构造函数在play中产生临时对象
test(const test &para) is called. i = 24//调用复制构造函数将临时对象复制给b
~test is called//play中的临时对象析构
************************************
test(k) is called. i = 10
test(const test &para) is called. i = 10
~test is called
************************************
test(k) is called. i = 20
test(const test &para) is called. i = 20
~test is called
************************************
~test is called//d 对象的析构
~test is called//c 对象的析构
~test is called//b 对象的析构
~test is called//a 对象的析构
请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值