C++ 授予访问权限

C++ Granting Access

在 C++ 中, 虽然授予访问权限,但不允许将变量从 protected 降级为 public,但它正在发生。

#include<iostream>
using namespace std;

class base {
    protected: int x;    // x is protected
};

class derived: private base { 
    public: base::x;     //demoting from protected to public must not happen
};

int main(){
    derived d1;
    d1.x=10;            //protected variable x is being accessed using an object**
    cout<<d1.x<<endl;
}

int 对象不是 protected,只是 name base::x

您的说法不正确"protected variable x is being accessed"。它不是。 derived::x 是一个 public 成员,仅 引用 base::x.

basepublicprotected 成员对 derived 可见,这是 protected 变量 base::x 可见的地方通过访问声明访问。