我有一个抽象类 A,我从它继承了许多类。在派生类中,我试图通过 A 指针访问 A 中的 protected 函数。但是我得到一个编译器错误。
class A
{
protected:
virtual void f()=0;
};
class D : public A
{
public:
D(A* aa) :mAPtr(aa){}
void g();
protected:
virtual void f();
private:
A* mAPtr; // ptr shows to some derived class instance
};
void D::f(){ }
void D::g()
{
mAPtr->f();
}
编译器错误提示:无法访问类 A 中声明的 protected 成员 A::f。
如果我将 mAPtr 声明为 D*,而不是 A*,则一切都会编译。我不明白为什么会这样。
最佳答案
依靠 private
访问对相同类型的不相关实例起作用。
依赖于protected
访问适用于相同类型(以及更多派生类型)的不相关实例。
但是,依赖于protected
访问不对基类型的不相关实例起作用。
[n3290: 11.5/1]:
When a friend or a member function of a derived class references a protected nonstatic member function or protected nonstatic data member of a base class, an access check applies in addition to those described earlier in clause 11. Except when forming a pointer to member (5.3.1), the access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class) (5.2.5). If the access is to form a pointer to member, the nested-name-specifier shall name the derived class (or any class derived from that class).
所以 D
或从 D
派生的东西,但不是 A
。
这是一个经常被质疑的关于 C++ 的可爱怪癖,但它的设计是为了尽量避免陷阱。毕竟,您不知道 *mAPtr
真正 有什么类型。
关于c++ - 如何从派生类通过基类 ptr 访问 protected 基类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7711237/