c++拷贝构造函数(对比于上一篇)

来源:互联网 发布:软件开发技术发展方向 编辑:程序博客网 时间:2024/05/17 22:41
#include <fstream>#include <string>using namespace std;ofstream out("HowMany.out");class HowMany {string name;  static int objectCount;public:HowMany(const string str=""):name(str) { objectCount++; }HowMany( HowMany& X){name=X.name+"COPY";objectCount++; out<<name<<endl;}  static void print(const string& msg = "") {    if(msg.size() != 0) out << msg << ": ";    out << "objectCount = "         << objectCount << endl;  }  ~HowMany() {    objectCount--;    print("~HowMany()");  }};int HowMany::objectCount = 0;// Pass and return BY VALUE:HowMany f(HowMany x) {  x.print("x argument inside f()");  return x;}int main() {  HowMany h("h");  HowMany::print("after construction of h");  HowMany h2("h2");  out<<"test1........"<<endl;  h2=f(h);  out<<"test2........"<<endl;    HowMany::print("after call to f()");} ///:~


输出结果为

after construction of h: objectCount = 1
test1........
hCOPY
x argument inside f(): objectCount = 3
hCOPYCOPY
~HowMany(): objectCount = 3
~HowMany(): objectCount = 2
test2........
after call to f(): objectCount = 2
~HowMany(): objectCount = 1
~HowMany(): objectCount = 0

在上一篇的基础上自定义了拷贝构造函数,从中我们可以看出在对象作为参数传递以及函数返回对象时都会调用拷贝构造函数,所以在函数调用最后会调用析构函数。这两篇对比学习一下会对位拷贝与深拷贝有更好的认识
原创粉丝点击