|
|
写了一个支持对象计数的类,代码如下:
- // file TestCounted.h
- #ifndef TESTCOUNTED_H_
- #define TESTCOUNTED_H_
- #include "Counted.h"
- namespace myclass
- {
- class TestCounted: Counted<TestCounted>
- {
- public:
- TestCounted();
- virtual ~TestCounted();
- using Counted<TestCounted>::objectCount;
- using Counted<TestCounted>::TooManyObjects;
- };
- }
- #endif /*TESTCOUNTED_H_*/
复制代码
- // file TestCounted.cpp
- #include "TestCounted.h"
- namespace myclass
- {
- template<typename TestCounted> const size_t Counted<TestCounted>::maxObjects = 2;
-
- TestCounted::TestCounted()
- {
- }
-
- TestCounted::~TestCounted()
- {
- }
- }
复制代码
- // file main.cpp
- #include <iostream>
- #include "TestCounted.h"
- #include "Counted.h"
- using namespace std;
- using namespace myclass;
- int main()
- {
- try
- {
- TestCounted t1;
- TestCounted t2;
- TestCounted t3;
- }
- catch(TestCounted::TooManyObjects& e)
- {
- cout << "The number of objects is " << TestCounted::objectCount() << "!\n";
- //throw;
- }
- return (0);
- }
复制代码
其中Counted是支持对象计数的基类,当对象个数超出设定的最大数值时,有一个异常将被抛出。设定的对象最大个数是2.TestCounted私有继承了Counted,因此具有了对象计数能力。
在main函数中,创建3个TestCounted对象,这将导致异常被抛出,通过try-catch块捕捉,然后输出此时的对象个数,却惊奇地发现输出的对象个数为0!也就是说,类的静态成员numObjects又被重新初始化了。编译环境是Gcc4.0.3。
请问这是什么原因造成的?是否属于C++的异常机制?谢谢! |
|