定义一个人工智能学院大一学生类,派生出男生和女生类,利用私有继承输出男生数量和女生数量数,其中可以结合构造函数和析构函数完成,要求在类内定义一个静态成员变量来统计学生总人数。代码尽量简单,要有中文注释
时间: 2024-02-06 14:03:43 浏览: 28
以下是一个简单的实现:
```c++
#include <iostream>
class AIStudent {
private:
// 静态成员变量,用来统计学生总人数
static int total;
public:
// 构造函数,每次创建对象时total加1
AIStudent() {
total++;
}
// 析构函数,每次销毁对象时total减1
virtual ~AIStudent() {
total--;
}
// 静态成员函数,返回学生总人数
static int getTotal() {
return total;
}
};
class MaleStudent: private AIStudent {
public:
MaleStudent() {}
~MaleStudent() {}
// 静态成员函数,返回男生数量
static int getMaleNum() {
return AIStudent::getTotal();
}
};
class FemaleStudent: private AIStudent {
public:
FemaleStudent() {}
~FemaleStudent() {}
// 静态成员函数,返回女生数量
static int getFemaleNum() {
return AIStudent::getTotal();
}
};
// 初始化静态成员变量total为0
int AIStudent::total = 0;
int main() {
// 创建两个MaleStudent对象和一个FemaleStudent对象
MaleStudent male1;
MaleStudent male2;
FemaleStudent female1;
// 输出男生数量和女生数量
std::cout << "Number of male students: " << MaleStudent::getMaleNum() << std::endl;
std::cout << "Number of female students: " << FemaleStudent::getFemaleNum() << std::endl;
return 0;
}
```
注释已经在代码中添加,主要思路是定义一个AIStudent类,包含一个静态成员变量total,用来统计学生总人数。MaleStudent和FemaleStudent类都私有继承自AIStudent类,这样它们就无法访问AIStudent的公有成员,但可以访问私有成员,包括total。
MaleStudent和FemaleStudent类中都没有其他成员变量和成员函数,它们只是利用继承关系来输出男生数量和女生数量。在main函数中创建了两个MaleStudent对象和一个FemaleStudent对象,然后分别调用getMaleNum()和getFemaleNum()静态成员函数来输出男生数量和女生数量。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)