小编Rup*_*ick的帖子

C++嵌套结构继承规则(访问受保护成员)

任何人都可以向我解释为什么(例如,"为什么语言是这样的?")以下代码在第二行有编译错误B::C::bar

class A
{
public:
    struct D
    {
        void call_foo (A &a)
        {
            a.foo ();
        }
    };

protected:
    void foo () {}
};

class B : public A
{
    struct C : public A::D
    {
        void bar (A &a, B &b)
        {
            b.foo (); // OK
            a.foo (); // Error. Huh?
            call_foo (a); // Ugly workaround
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

当且仅当基指针的类型恰好是封闭类型(而不是某些父类型)时,似乎方法可以安全地在父类中使用受保护的方法.

这看起来很奇怪.为什么这种语言呢?

c++ inheritance protected language-lawyer

10
推荐指数
1
解决办法
1033
查看次数

标签 统计

c++ ×1

inheritance ×1

language-lawyer ×1

protected ×1