目录
代码源码:
// 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 ¶){
i = para.i;
cout << "test(const test ¶) 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 ¶) is called. i = 24//调用复制构造函数,把临时对象复制到a
~test is called//play中的临时对象析构
************************************
test(const test ¶) is called. i = 24//调用复制构造函数在play中产生临时对象
test(const test ¶) is called. i = 24//调用复制构造函数将临时对象复制给b
~test is called//play中的临时对象析构
************************************
test(k) is called. i = 10
test(const test ¶) is called. i = 10
~test is called
************************************
test(k) is called. i = 20
test(const test ¶) is called. i = 20
~test is called
************************************
~test is called//d 对象的析构
~test is called//c 对象的析构
~test is called//b 对象的析构
~test is called//a 对象的析构
请按任意键继续. . .