c/c++语言开发共享C++编程之引用和拷贝构造函数、按值传递和返回、位拷贝与初始化等实例

对于传递和返回大的简单结构有了可使用的方法 一个类在任何时候都知道她存在多少个对象 //: c11:howmany.cpp // from thinking in c++, 2nd editi

对于传递和返回大的简单结构有了可使用的方法

一个类在任何时候都知道她存在多少个对象

  //: c11:howmany.cpp  // from thinking in c++, 2nd edition  // available at https://www.bruceeckel.com  // (c) bruce eckel 2000  // copyright notice in copyright.txt  // a class that counts its objects  #include   #include   using namespace std;  ofstream out("howmany.out");    class howmany {   static int objectcount;  public:   howmany() { objectcount++; }   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;   howmany::print("after construction of h");   howmany h2 = f(h);   howmany::print("after call to f()");  } ///:~

howmany类包括一个静态变量int objectcount和一个用于报告这个变量的

静态成员函数print(),这个函数有一个可选择的消息参数

输出不是我们期望的那样

after construction of h: objectcount = 1

x argument inside f(): objectcount = 1

~howmany(): objectcount = 0

after call to f(): objectcount = 0

~howmany(): objectcount = -1

~howmany(): objectcount = -2

在h生成以后,对象数是1,这是对的

原来的对象h存在函数框架之外,同时在函数体内又增加了一个对象,这个对象

是通过传值方式传入的对象的拷贝

在对f()的调用的最后,当局部对象出了其范围时,析构函数就被调用,析构

函数使objectcount减小

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/607955.html

(0)
上一篇 2021年5月14日
下一篇 2021年5月14日

精彩推荐