对于传递和返回大的简单结构有了可使用的方法
一个类在任何时候都知道她存在多少个对象
//: c11:howmany.cpp
// from thinking in c++, 2nd edition
// available at http://www.51sjk.com/Upload/Articles/1/0/251/251209_20210626000555044.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减小
张小咩的小姿生活