第2关:保护继承 —— 学生信息类
时间: 2023-10-17 11:21:42 浏览: 116
保护继承是指子类继承父类的成员,但是只有类内和友元可以访问这些成员,对于类外部的其他代码是不可见的。这样可以保护父类的实现细节,同时也可以在子类中使用这些成员。
下面以学生信息类为例,演示如何使用保护继承。
```c++
#include <iostream>
#include <string>
using namespace std;
// 父类:人类
class Person {
public:
Person(string name, int age) : m_name(name), m_age(age) {}
void showInfo() {
cout << "姓名:" << m_name << endl;
cout << "年龄:" << m_age << endl;
}
protected: // 保护成员
string m_name; // 姓名
int m_age; // 年龄
};
// 子类:学生类
class Student : protected Person {
public:
Student(string name, int age, int score) : Person(name, age), m_score(score) {}
void showInfo() {
Person::showInfo(); // 调用父类的 showInfo 函数
cout << "成绩:" << m_score << endl;
}
private:
int m_score; // 成绩
};
int main() {
Student s("小明", 18, 90);
s.showInfo(); // 调用子类的 showInfo 函数
return 0;
}
```
在上面的例子中,父类 `Person` 中的成员 `m_name` 和 `m_age` 被声明为保护成员,子类 `Student` 继承了这两个成员。在子类中,我们使用 `protected` 访问修饰符将父类的成员变量和成员函数设置为保护成员,这样子类就可以访问这些成员了。
在子类中,我们重写了 `showInfo` 函数,并在其中调用了父类的 `showInfo` 函数,然后输出了子类新增的成员 `m_score`。最后在 `main` 函数中,我们创建了一个 `Student` 对象,并调用了 `showInfo` 函数,输出了学生的信息。
在这个例子中,我们使用保护继承来访问父类的成员,这样可以保护父类的实现细节,同时也可以在子类中使用这些成员。