对于传递和返回大的简单结构有了可使用的方法
一个类在任何时候都知道她存在多少个对象
//: 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减小
发表评论