代码是这样的:
#include <iostream>
using namespace std;
class Example
{
private:
int test;
public:
Example()
{
cout<<"Constructing.."<<endl;
} //无参构造函数
Example(int _test)
{
test = _test;
cout<<"Constructing..."<<endl;
} //有参构造函数
Example(Example &exa)
{
cout<<"Copy constructing..."<<endl;
}
Example Fun(Example ex){return ex;} //函数的返回值为对象
int getTest(){return test;}
};
int main()
{
Example a(7);
cout<<"a.Test = "<<a.getTest()<<endl;
Example b;
b = a.Fun(a);
cout<<"b.Test = "<<a.getTest()<<endl;
return 0;
}
运行结果是这样:
第一条输出是初始化对象a时

本文探讨了C++中当对象作为函数返回值时,系统如何自动调用拷贝构造函数。通过代码示例,解释了在函数调用过程中两次拷贝构造函数的调用原因:一次是传参时创建临时对象,另一次是返回值对象赋值给接收者时。分析了临时对象的生命周期和拷贝过程。

674





