继承的访问控制_保护继承_保护继承(C++语言)

来源:互联网 发布:cnnic证书 知乎 编辑:程序博客网 时间:2024/05/16 06:50

在保护继承中,

基类的公有成员在派生类中成为保护成员,

基类的保护成员在派生类中仍为保护成员,

所以,派生类的所有成员在类的外部都无法访问它们。

-----------------------------------------------------------------------------

例如,下面程序实现类Derived对基类Base的保护继承,

仔细理解保护继承后派生类对象如何访问基类的成员。

#include <iostream>
using namespace std;
class Base
{
private:
int a;
protected:
int b;//--------------定义基类保护成员
public:
int c;
void setab(int x, int y)//---------------定义基类公有成员函数
{
a = x;
b = y;
}
int geta()
{
return a;
}
};


class Derived :protected Base//--------------类Derived保护继承类Base
{
private://----------------定义派生类私有成员
int c;
public:
void setabc(int m, int n, int l)//----------定义派生类公有成员函数
{
setab(m, n);
b = m;//-------------可直接访问从基类中保护继承的成员
c = l;
}
int getc()
{
c = c + b*geta();//--------通过基类的成员函数间接访问基类的私有成员
return c;
}
};


int main()
{
Derived ob;
// ob.setab(12,12);//非法,不能通过类外对象访问从基类保护继承来的成员
ob.setabc(12, 12, 5);//------合法,访问派生类本身的成员函数
cout << "the result of ob.getc() is :" << ob.getc() << endl;
system("pause");
return 0;
}

--------------------------------------------------------------------------------------------------------------------

运行结果为:149

--------------------------------------------------------------------------------------------------------------------

在上述代码中,

类Base定义了保护成员变量b,

类Derived保护继承自类Base。

在主函数main()中,

由类Derived创建对象ob,

该对象直接访问类Base的公有成员函数setab()时会出现错误,

这是因为经过保护继承后,

类Base的公有成员在类Derived中成为保护成员,

而外部函数是不能直接访问保护成员的,

需要通过调用公有成员函数来实现。

0 0