当需要用同类的对象来创建一个新的对象的时候,那个类的拷贝构造函数就会被调用来构造这个对象。
#include <iostream>
using namespace std;
static int objectCount =0;
class HowMany{
public:
HowMany(){objectCount++;print("HowMany()");}
HowMany(int i){ objectCount++;print("HowMany(int)");}
void print(const string& msg =""){
if(msg.size()!=0) cout <<msg<<":";
cout<<"ObjectCount = "<<objectCount<<endl;
}
~HowMany(){ objectCount--;print("~HowMany()");
}
};
//Pass and return BY VALUE
HowMany f(HowMany x) {
cout<<"begin of f";
x.print("x argument insides f()");
cout<<"end of f()"<<endl;
return 0;
}
int main(int arg, char* avg[]){
HowMany h;
h.print("after construction of h");
HowMany h2 =h;
h.print("after call to h");
//f(h);
//h.print("after call to f()");
return 0;
}
输出结果:
HowMany():ObjectCount = 1
after construction of h:ObjectCount = 1
after call to h:ObjectCount = 1
~HowMany():ObjectCount = 0
~HowMany():ObjectCount = -1
关于程序设计基石与实践更多讨论与交流,敬请关注本博客和新浪微博songzi_tea.