下面是一段令我恼火的代码示例:
class Base {
protected:
virtual void foo() = 0;
};
class Derived : public Base {
private:
Base *b; /* Initialized by constructor, not shown here
Intended to store a pointer on an instance of any derived class of Base */
protected:
virtual void foo() { /* Some implementation */ };
virtual void foo2() {
this->b->foo(); /* Compilator sets an error: 'virtual void Base::foo() is protected' */
}
};
如何访问 protected 重写函数?
感谢您的帮助。 :o)
最佳答案
基类中的 protected 成员只能由当前对象访问。
因此,您可以调用 this->foo()
,但不允许调用 this->b->foo()
。这与 Derived
是否为 foo
提供实现无关。
此限制背后的原因是,否则很容易绕过 protected 访问。您只需创建一个像 Derived
这样的类,突然间您就可以访问其他类(例如 OtherDerived
)的部分,这些部分本应不被外部人员访问。
关于c++ - 如何从派生类访问基类中的 protected 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4672438/