问题描述
我有抽象类A,我从中继承了一些类。在派生类中,我试图访问A槽A指针中的保护函数。但我得到一个编译器错误。
I have abstract class A, from which I inherit a number of classes. In the derived classes I am trying to access protected function in A trough A pointer. But I get a compiler error.
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 :: f A。
The compiler error says : cannot access protected member A::f declared in class A.
如果我声明mAPtr为D *,而不是A *所有的编译。
If I declare mAPtr to be D*, instead A* everything compiles. And I don't understand why is this.
推荐答案
依赖私人
访问对同一类型的不相关实例的访问。
Relying on private
access works on unrelated instances of the same type.
依赖 protected
但是,依赖 protected
访问 em>工作于基本类型的无关实例。
However, relying on protected
access does not work on unrelated instances of a base type.
所以 D
或派生自 D
的东西, code> A 。
So D
or something derived from D
, but not A
.
这是一个可疑的奇怪的C ++,但是设计,以避免陷阱。毕竟,你不知道 * mAPtr
真的类型。
It's an oft-questioned cute oddity about C++ that nonetheless is designed to try to avoid pitfalls. After all, you don't know what type *mAPtr
really has.
这篇关于如何访问受保护的基类函数,从派生类通过基类ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!