64,639
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"无参构造函数"<<endl;
}
A(const A& a)
{
cout<<"拷贝构造函数"<<endl;
}
A& operator = (const A& a)
{
cout<<"赋值运算符重载"<<endl;
return *this;
}
~A()
{
cout<<"析构函数"<<endl;
}
private:
};
const A boo(const A a)
{
cout<<"A tmp = a"<<endl;
A tmp = a;//调用拷贝构造函数
cout<<"return tmp"<<endl;
return tmp;//外部会自动定义一个临时变量,以tmp初始化,所以调用拷贝构造函数
}
int main(int argc,char* argv[])
{
cout<<"A a"<<endl;
A a;//调用无参构造函数
cout<<"A b(a)"<<endl;
A b(a);//调用拷贝构造函数
cout<<"-----------------------------------------------"<<endl;
b=boo(a);//当把a值传递给形参时,会调用拷贝构造函数;返回时,会定义临时变量以函数内返回值初始化
system("pause");
return 0;
}
执行结果:
A a
无参构造函数
A b(a)
拷贝构造函数
-----------------------------------------------
拷贝构造函数
A tmp = a
拷贝构造函数
return tmp
拷贝构造函数
析构函数
析构函数
赋值运算符重载
析构函数
请按任意键继续. . .