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

#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

在上一篇的基础上自定义了拷贝构造函数,从中我们可以看出在对象作为参数传递以及函数返回对象时都会调用拷贝构造函数,所以在函数调用最后会调用析构函数。这两篇对比学习一下会对位拷贝与深拷贝有更好的认识
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值