保护继承
保护继承相对于公有继承,访问性有所降低,父类的公有成员在子类中变成了保护成员,也就无法在外部通过一个对象访问父类成员了,但是对于这个子类的子类仍然是可见的(因为可见性只是降到了 protected )。
如果要保护继承一个类,只需继承时在类名前面加上 protected 关键字即可。
例如:
class Base
{
public:
int A;
};
class D1 : protected Base // 保护继承 Base 类
{
/* …… */
};
int main()
{
D1 d;
d.A = 10; // 尝试访问 D1 的基类 Base 中的 A 成员,但是由于是保护继承,所以这样做是错误的。
}
在保护继承中如果想通过子类访问父类的成员,那就只能在子类中增加一些 get 、set 函数来实现了。
例如:
/* Base类的定义同上 */
class D1 : protected Base
{
public:
void SetA(int a); // 设置 Base 类中 A 的值
int GetA(); // 获取 Base 类中 A 的值
};
void D1::SetA(int a)
{
A = a;
}
int D1::GetA()
{
return A;
}
int main()
{
Student st;
st.SetA(10); // 将 Base 类的 A 成员设置为 10
}
编程要求
在右侧编辑器中的Begin-End
之间补充代码,采用保护继承设计学生信息类,并实现 Set 和 PrintSID 函数,具体要求如下:
-
Student 类公有成员函数:
void PrintSID()
,函数输出成员变量 SID 的值,输出格式为:学号:SID
。 -
普通函数:
Set(int sid,string name,Student *ptr)
,它用前两个参数设置 ptr 对象的 SID 和 Name(继承 People 拥有的属性)属性值。
现在已有一个基类 People,它有一个公有成员变量姓名 Name,一个公有成员函数 PrintName(函数的功能是打印出 Name 的值)。
class People
{
public:
string Name;
void PrintName();
};
void People::PrintName()
{
cout << "姓名:" << Name << endl;
}
-
#include "people.h" // People 类定义在这里面 #include <string> #include <iostream> using namespace std; /********** Begin **********/ //保护继承 People class Student : protected People { public: int SID; void PrintSID(); void Setname(string name) { this->Name = name; } //添加一个 Set 函数来设置父类的 Name 成员 }; /********* End *********/ void Student::PrintSID() { /********* Begin *********/ //输出学号 SID cout << "学号:" << SID << endl; /********* End *********/ } void Set(int sid,string name,Student *ptr) { /********* Begin *********/ //给 ptr 对象的两个属性赋值 ptr->Setname(name); ptr->SID = sid; /********* End *********/ }