引入
首先我们看一段代码:
static int count =0;
class howmany
{
public:
howmany(){
count++;
std::cout<<"constructor:"<<endl;
}
void print(const string& str )
{
std::cout<<str<<" "<<count<<endl;
}
~howmany()
{
count--;
std::cout<<"destructor:"<<count<<endl;
}
};
howmany fun(howmany x)
{
cout<<"beginning of fun"<<endl;
x.print("print x in fun");
cout<<"end of x"<<endl;
return x;
}
int main()
{
howmany h;
h.print("int main after build A");
howmany z=fun(h);
h.print("int main last line");
}
这段代码执行的显示的内容是:
进行了一次constructor的调用,进行了三次destruction的调用
这样岂不是很矛盾?n次构造对应n次析构啊?
所以结论是编译器进行了两次默认的构造但是没有调用默认构造函数
在main中,howmany z=fun(h)
进行了一次构造,在fun里面也进行了一次构造,这两次构造叫做:拷贝构造
顾名思义就是以拷贝的方式构造一个对象
基础定义
函数原型:
T::T(const T & );
默认的拷贝构造函成员数会拷贝每一个成员变量;