首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于《C++编程思想》第一卷中的 异常

2013-10-21 
关于《C++编程思想》第一卷中的 错误最近在看《C++编程思想》中的拷贝构造函数,发现第十一章11.3.1.4节的例子/

关于《C++编程思想》第一卷中的 错误
最近在看《C++编程思想》中的拷贝构造函数,发现第十一章11.3.1.4节的例子//:C11:HowMany.cpp书中给出结果与我自己运行的结果不同,请各位看一下原因,顺便分析一下构造函数和析构函数的工作原理。附上代码:

#include <iostream>
#include <string>
using namespace std;

class HowMany
{
static int objectCount;
public:
HowMany()
{
objectCount++;
}

static void print(const string& msg = "")
{
if (msg.size() != 0)
{
cout<<msg<<": ";
}
cout<<"objectCount = "<<objectCount<<endl;
}

~HowMany()
{
objectCount--;
print("~HowMany()");
}
};

int HowMany::objectCount = 0;

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()");

system("pause");
}


书中的结果是
after construction of h:objectCount = 1
x argument inside f(): objectCount = 1
~HowMany(): objectionCount = 0
after call to f(): objectionCount = 0
~HowMany(): objectionCount = -1
~HowMany(): objectionCount = -2


我的结果是
after construction of h:objectCount = 1
x argument inside f(): objectCount = 1
~HowMany(): objectionCount = 0
after call to f(): objectionCount = 0


c++ 析构函数
[解决办法]
上面有点错误,应该是,对象的析构在system("pause");之后才发生

热点排行