设计并实现一个ObjectCounter类,要求: (1)对系统中现存的本类实例计数; (2)每个对象都有唯一的整型ID,按照创建的次序建立; (3)获取当前系统中本类对象的个数; (4)获取每个对象的ID。编写测试程序
时间: 2023-11-28 09:50:04 浏览: 45
下面是一个可能的ObjectCounter类的实现:
```cpp
class ObjectCounter {
public:
ObjectCounter() {
id_ = count_++;
}
virtual ~ObjectCounter() {
--count_;
}
static size_t getCount() {
return count_;
}
int getID() const {
return id_;
}
private:
static size_t count_;
size_t id_;
};
size_t ObjectCounter::count_ = 0;
```
这个类有一个静态成员变量 `count_`,用于记录当前系统中本类对象的个数。每次创建一个新对象时,它的构造函数会将 `count_` 增加,同时为该对象分配一个唯一的ID。当对象被销毁时,`count_` 会减少。
使用该类的示例测试程序:
```cpp
#include <iostream>
#include <vector>
class MyClass : public ObjectCounter {
public:
MyClass() {
std::cout << "MyClass #" << getID() << " created" << std::endl;
}
~MyClass() {
std::cout << "MyClass #" << getID() << " destroyed" << std::endl;
}
};
int main() {
std::vector<MyClass*> objs;
for (int i = 0; i < 5; ++i) {
objs.push_back(new MyClass());
}
std::cout << "Number of MyClass objects: " << ObjectCounter::getCount() << std::endl;
for (auto obj : objs) {
std::cout << "Object #" << obj->getID() << std::endl;
delete obj;
}
std::cout << "Number of MyClass objects: " << ObjectCounter::getCount() << std::endl;
return 0;
}
```
输出结果为:
```
MyClass #0 created
MyClass #1 created
MyClass #2 created
MyClass #3 created
MyClass #4 created
Number of MyClass objects: 5
Object #0
MyClass #0 destroyed
Object #1
MyClass #1 destroyed
Object #2
MyClass #2 destroyed
Object #3
MyClass #3 destroyed
Object #4
MyClass #4 destroyed
Number of MyClass objects: 0
```
阅读全文