简体   繁体   English

访问指定为private的基类的公共静态成员

[英]Accessing public static members of a base class specified as private

I'm learning C++. 我正在学习C ++。 The documentation docs.microsoft.com/en-us/cpp/cpp/member-access-control-cpp says: docs.microsoft.com/en-us/cpp/cpp/member-access-control-cpp文档说:

When you specify a base class as private, it affects only nonstatic members. 将基类指定为私有时,它仅影响非静态成员。 Public static members are still accessible in the derived classes. 公共静态成员仍可在派生类中访问。

However, the following code slightly adjusted from the example following the previous quote cause error C2247: 但是,以下代码从前一个引用之后的示例略微调整导致错误C2247:

'Base::y' not accessible because 'Derived1' uses 'private' to inherit from 'Base'. 'base :: y'无法访问,因为'Derived1'使用'private'继承'Base'。

I will appreciate any help with this situation. 对于这种情况,我将不胜感激。

class Base
{
public:
    int x;             
    static int y;      
};

class Derived1 : private Base
{
};

class Derived2 : public Derived1
{
public:
    int ShowCount();    
};

int Derived2::ShowCount()
{
    int cCount = Base::y;       
    return cCount;
}

That documentation is a little misleading. 该文档有点误导。

The correct compiler behaviour is for Base::y and Base::x to both be inaccessible in Derived , if you use that notation to attempt to reach the static member. 正确的编译器行为是Base::y Base::xDerived 不可访问,如果您使用该表示法尝试访问static成员。

But you can reach it via the global namespace (thereby circumventing Derived1 ) by using another scope resolution operator: 但是您可以通过使用另一个范围解析运算符通过全局命名空间 (从而规避Derived1访问它:

int Derived2::ShowCount()
{
    int cCount = ::Base::y;       
    return cCount;
}

Finally, don't forget to define y somewhere if you want the link stage to be successful. 最后,如果您希望链接阶段成功,请不要忘记在某处定义 y

Change this: 改变这个:

Base::y;

to this; 对此;

::Base::y;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM