用c++定义一个人工智能学院大一学生类,派生出男生和女生类,利用私有继承输出男生数量和女生数量数,其中可以结合构造函数和析构函数完成,要求在类内定义一个静态成员变量来统计学生总人数。
时间: 2024-02-13 09:01:43 浏览: 196
以下是一个可能的实现:
```c++
#include <iostream>
class AI_Student {
private:
static int total_num; // 静态成员变量,用于统计学生总人数
protected:
AI_Student() {
total_num++;
}
~AI_Student() {
total_num--;
}
public:
virtual void display() = 0;
static void display_num() {
std::cout << "Total students: " << total_num << std::endl;
}
};
int AI_Student::total_num = 0;
class Male_Student : private AI_Student {
private:
static int male_num;
public:
Male_Student() {
male_num++;
}
~Male_Student() {
male_num--;
}
void display() {
std::cout << "Male students: " << male_num << std::endl;
}
};
int Male_Student::male_num = 0;
class Female_Student : private AI_Student {
private:
static int female_num;
public:
Female_Student() {
female_num++;
}
~Female_Student() {
female_num--;
}
void display() {
std::cout << "Female students: " << female_num << std::endl;
}
};
int Female_Student::female_num = 0;
int main() {
AI_Student* p1 = new Male_Student();
AI_Student* p2 = new Female_Student();
AI_Student::display_num(); // 输出总人数
p1->display(); // 输出男生数量
p2->display(); // 输出女生数量
delete p1;
AI_Student::display_num(); // 输出总人数
p2->display(); // 输出女生数量
delete p2;
AI_Student::display_num(); // 输出总人数
return 0;
}
```
输出结果:
```
Total students: 2
Male students: 1
Female students: 1
Total students: 1
Female students: 1
Total students: 0
```
阅读全文