对于每一个类,如果程序员不显式声明和定义,C++编译器会自动产生以下四种函数。
构造函数:A()
析构函数:~A()
复制构造函数:A(const A &a)
赋值构造函数:operator = (const A &a)
如果在代码中自己显式定义了,则调用程序中定义的函数,如下面代码所示:
# include <iostream>
using namespace std;
//测试复制构造函数和赋值函数
class TestFun
{
private:
int num;
public:
TestFun()
{
cout<<"this is default constructor"<<endl;
}
~TestFun()
{
cout<<"this is disconstructor"<<endl;
cout<< num << endl;
}
TestFun(const TestFun &fun)
{
cout<<"this is copy constructor"<<endl;
}
void operator = (const TestFun &fun)
{
cout<<"this is operator constructor"<<endl;
}
void setnum(int n)
{
num = n;
}
};
void main()
{
TestFun Fun1; //调用默认构造函数
TestFun Fun2(Fun1); //调用复制构造函数
TestFun Fun3 = Fun1; //调用复制构造函数
TestFun Fun4; //调用默认构造函数
Fun4 = Fun1; //调用赋值构造函数
Fun1.setnum(1);
Fun2.setnum(2);
Fun3.setnum(3);
Fun4.setnum(4);
}
结果:
this is default constructor
this is copy constructor
this is copy constructor
this is default constructor
this is operator constructor
this is disconstructor
4
this is disconstructor
3
this is disconstructor
2
this is disconstructor
1