当我在基类中声明 protected 成员并在派生类中继承为私有(private)时,不允许访问该成员
class base{
protected:
int a;
};
class derived : public base
{
protected:
int b;
public:
derived():base(){ a=0; b=0;}
void show(){cout<<"a= "<<a<<"\tb= "<<b;}
};
int main ()
{
derived d;
d.a=10; //error: 'int base::a' is protected within this context
d.show();
}
但是当我编写派生类时,授予“a”的公共(public)访问权限(在基类中 protected )
class derived : public base
{
protected:
int b;
public:
base::a;
};
int main ()
{
derived d;
d.a=20; // no error
}
现在我可以更改 main() 中“a”的值,不会出现任何错误。
我在c++完全引用书上看到,授予访问权限会恢复访问权限,但不能提高或降低访问状态。
谁能告诉我为什么我能够访问基类的 protected 成员,私有(private)继承,然后像派生类的公共(public)变量一样提供公共(public)访问权限(这是否违反封装,即 protected 成员应该恢复为 protected )。 如果我的理解不正确,请指导我
最佳答案
关于c++ - 在派生类 C++ 中将基类的 protected 成员访问声明为 public,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47463027/