定义一个人工智能学院大一学生类,派生出男生和女生类,利用私有继承输出男生数量和女生数量数,其中可以结合构造函数和析构函数完成,要求在类内定义一个静态成员变量来统计学生总人数。
时间: 2024-02-28 18:57:37 浏览: 46
好的,我会为您解答这个问题。
首先,我们可以定义一个人工智能学院大一学生类,命名为 AI_Student,如下所示:
```c++
class AI_Student {
public:
AI_Student(); // 构造函数
~AI_Student(); // 析构函数
private:
static int count; // 静态成员变量,记录学生总人数
};
```
在这个类中,我们定义了一个构造函数和析构函数,并且定义了一个私有的静态成员变量 count,用于记录学生总人数。
接下来,我们可以派生出男生和女生类,分别命名为 AI_Boy 和 AI_Girl,使用私有继承,如下所示:
```c++
class AI_Boy : private AI_Student {
public:
AI_Boy(); // 构造函数
~AI_Boy(); // 析构函数
void showNum(); // 输出男生数量
};
class AI_Girl : private AI_Student {
public:
AI_Girl(); // 构造函数
~AI_Girl(); // 析构函数
void showNum(); // 输出女生数量
};
```
在这两个类中,我们定义了构造函数和析构函数,并且分别添加了一个成员函数 showNum,用于输出男生数量和女生数量。
接下来,我们需要在类的实现文件中实现这些函数,如下所示:
```c++
#include "AI_Student.h"
#include <iostream>
int AI_Student::count = 0;
AI_Student::AI_Student() {
++count;
}
AI_Student::~AI_Student() {
--count;
}
AI_Boy::AI_Boy() {
std::cout << "一个男生加入了人工智能学院" << std::endl;
}
AI_Boy::~AI_Boy() {
std::cout << "一个男生离开了人工智能学院" << std::endl;
}
void AI_Boy::showNum() {
std::cout << "男生数量:" << count << std::endl;
}
AI_Girl::AI_Girl() {
std::cout << "一个女生加入了人工智能学院" << std::endl;
}
AI_Girl::~AI_Girl() {
std::cout << "一个女生离开了人工智能学院" << std::endl;
}
void AI_Girl::showNum() {
std::cout << "女生数量:" << count << std::endl;
}
```
在这些实现文件中,我们实现了构造函数和析构函数,并且在构造函数中累加了学生总人数,在析构函数中减去了学生总人数。同时,在男生和女生类的构造函数中输出了加入学院的信息,在析构函数中输出了离开学院的信息。在 showNum 函数中,我们输出了男生或女生的数量。
最后,我们可以在主函数中使用这些类,并输出结果:
```c++
#include "AI_Student.h"
int main() {
AI_Boy b1, b2, b3;
AI_Girl g1, g2;
b1.showNum();
g1.showNum();
return 0;
}
```
在这个主函数中,我们分别生成了 3 个男生和 2 个女生,然后分别调用了 showNum 函数,输出了男生和女生的数量。输出的结果应该是:
```
一个男生加入了人工智能学院
一个男生加入了人工智能学院
一个男生加入了人工智能学院
一个女生加入了人工智能学院
一个女生加入了人工智能学院
男生数量:3
女生数量:2
一个男生离开了人工智能学院
一个男生离开了人工智能学院
一个男生离开了人工智能学院
一个女生离开了人工智能学院
一个女生离开了人工智能学院
```
这样,我们就完成了这个问题的解答。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)