2.请设计并实现类 A -Bx-C,要求支持统计各类的实时对象数量。
时间: 2024-02-16 14:02:20 浏览: 18
可以使用类的静态成员变量来记录对象数量,每次创建对象时增加计数器,销毁对象时减少计数器。具体实现如下:
```c++
#include <iostream>
using namespace std;
class A {
public:
A() {
countA++;
}
~A() {
countA--;
}
static int getCountA() {
return countA;
}
private:
static int countA;
};
int A::countA = 0;
class B {
public:
B() {
countB++;
}
~B() {
countB--;
}
static int getCountB() {
return countB;
}
private:
static int countB;
};
int B::countB = 0;
class C {
public:
C() {
countC++;
}
~C() {
countC--;
}
static int getCountC() {
return countC;
}
private:
static int countC;
};
int C::countC = 0;
class ABC {
public:
ABC() {
a = new A();
b = new B();
c = new C();
}
~ABC() {
delete a;
delete b;
delete c;
}
private:
A* a;
B* b;
C* c;
};
int main() {
ABC obj1;
ABC obj2;
cout << "A: " << A::getCountA() << endl;
cout << "B: " << B::getCountB() << endl;
cout << "C: " << C::getCountC() << endl;
return 0;
}
```
其中,类 A、B、C 分别表示三种不同的对象,ABC 类是由这三种对象组成的一个复合对象。每当创建一个 A、B、C 对象时,对应的计数器会加 1;每当销毁一个 A、B、C 对象时,对应的计数器会减 1。ABC 对象的创建和销毁都会触发 A、B、C 对象的创建和销毁,从而实现了统计各类实时对象数量的功能。在程序最后,我们可以通过 getCountA、getCountB、getCountC 函数获取当前各种对象的数量并输出。
相关推荐
![caj](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)