公共/受保护/私有继承的麻烦

tem*_*boy 2 c++ inheritance protected private-members

我正在尝试一个简单的C++继承示例.但我无法理解.当我尝试B从类继承的类的受保护成员时,A它表示A::baz受保护.

#include <iostream>

class A {
    public:
        int foo;
        int bar;
    protected:
        int baz;
        int buzz;
    private:
        int privfoo;
        int privbar;
};

class B : protected A {}; // protected members go to class B, right?

int main() {
    B b;

    b.baz; // here is the error [A::baz is protected]
}
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到我做错的事.我试图改变class B : protected A: public A,但它仍然无法正常工作.

Dou*_* T. 5

受保护的继承只会影响类的客户端如何看到基类的公共接口.受保护的继承将基类的公共成员标记为受保护的继承类的用户.

因此,baz在您的示例中不公开,它受B保护,因此编译错误.

  • @ user6607默认情况下它是私有的 (5认同)