设计并实现一个ObjectCounter类,要求: (1)对系统中现存的本类实例计数; (2)每个对象都有唯一的整型ID,按照创建的次序建立; (3)获取当前系统中本类对象的个数; (4)获取每个对象的ID; 编写测试程序,使用c++编写
时间: 2023-11-28 13:50:19 浏览: 43
下面是ObjectCounter类的实现:
```cpp
class ObjectCounter {
public:
ObjectCounter()
{
++count;
id = count;
}
virtual ~ObjectCounter()
{
--count;
}
static int getCount()
{
return count;
}
int getId()
{
return id;
}
private:
static int count;
int id;
};
int ObjectCounter::count = 0;
```
使用方法很简单,只需要在类的定义中继承ObjectCounter即可,例如:
```cpp
class MyClass : public ObjectCounter {
public:
MyClass() {}
~MyClass() {}
};
```
这样就可以统计MyClass的实例个数并获取每个实例的唯一ID了。
下面是一个测试程序:
```cpp
int main()
{
MyClass* p1 = new MyClass();
MyClass* p2 = new MyClass();
MyClass* p3 = new MyClass();
cout << "Object count: " << MyClass::getCount() << endl;
cout << "p1 ID: " << p1->getId() << endl;
cout << "p2 ID: " << p2->getId() << endl;
cout << "p3 ID: " << p3->getId() << endl;
delete p1;
delete p2;
delete p3;
cout << "Object count: " << MyClass::getCount() << endl;
return 0;
}
```
输出如下:
```
Object count: 3
p1 ID: 1
p2 ID: 2
p3 ID: 3
Object count: 0
```
阅读全文