封装学生类,并派生男学生(女学生,优秀学生等)
时间: 2024-01-22 09:09:08 浏览: 21
下面是一个简单的示例,封装了一个学生类,以及派生出男学生、女学生、优秀学生等子类。示例中仅包含部分属性和方法,仅供参考。
```cpp
// 学生类
class Student {
protected:
string name; // 姓名
int age; // 年龄
char gender; // 性别
public:
Student(string n, int a, char g) : name(n), age(a), gender(g) {}
string getName() const {
return name;
}
int getAge() const {
return age;
}
char getGender() const {
return gender;
}
virtual void study() {
cout << "学生 " << name << " 正在学习" << endl;
}
};
// 男学生类,继承自学生类
class MaleStudent : public Student {
public:
MaleStudent(string n, int a) : Student(n, a, 'M') {}
void study() override {
cout << "男学生 " << name << " 正在学习" << endl;
}
};
// 女学生类,继承自学生类
class FemaleStudent : public Student {
public:
FemaleStudent(string n, int a) : Student(n, a, 'F') {}
void study() override {
cout << "女学生 " << name << " 正在学习" << endl;
}
};
// 优秀学生类,继承自学生类
class ExcellentStudent : public Student {
private:
int score; // 成绩
public:
ExcellentStudent(string n, int a, char g, int s) : Student(n, a, g), score(s) {}
int getScore() const {
return score;
}
void study() override {
cout << "优秀学生 " << name << " 正在学习" << endl;
}
void showScore() {
cout << "学生 " << name << " 的成绩是 " << score << endl;
}
};
```
使用示例:
```cpp
int main() {
Student *s1 = new MaleStudent("Tom", 20);
Student *s2 = new FemaleStudent("Lucy", 19);
Student *s3 = new ExcellentStudent("Mike", 21, 'M', 95);
s1->study(); // 输出:男学生 Tom 正在学习
s2->study(); // 输出:女学生 Lucy 正在学习
s3->study(); // 输出:优秀学生 Mike 正在学习
ExcellentStudent *s4 = new ExcellentStudent("John", 22, 'M', 88);
s4->showScore(); // 输出:学生 John 的成绩是 88
delete s1;
delete s2;
delete s3;
delete s4;
return 0;
}
```