不能调用基类保护函数? [英] cannot call base class protected functions?
问题描述
我无法在我的基类中调用protected函数。为什么?它看起来像这样:
I cant call protected function in my base class. Why? It looks something like this:
class B : B2
{
public:
virtual f1(B*)=0;
protected:
virtual f2(B*) { codehere(); }
}
class D : public B
{
public:
virtual f1(B*b) { return f2(b); }
protected:
virtual f2(B*b) { return b->f2(this); }
}
在pmvc中我得到错误错误C2248:'name :: class: :f2':无法访问类'name :: class'中声明的受保护成员
In msvc I get the error error C2248: 'name::class::f2' : cannot access protected member declared in class 'name::class'
在gcc中我得到错误:'virtual int name :: class :: f2 '受到保护。
In gcc I get error: 'virtual int name::class::f2()' is protected.
为什么?我认为受保护成员的要点是为派生类调用。
Why is that? I thought the point of protected members is for derived classes to call.
推荐答案
受保护的成员函数只能在基类中调用或在其派生类中。你不能在你的班级外面打电话。外部调用意味着调用类类型变量的成员函数。
Protected member functions can only be called inside the base class or in its derived class. You cannot call them outside your class. Outside calling means calling a member function of a class-typed variable.
因此
virtual f1(B*b) { return f2(b); }
是确定的,因为f2对类本身进行操作。 (内部呼叫)
is ok, because f2 operates on the class itself. (called inside)
但
virtual f2(B*b) { return b->f2(this); }
无法编译,因为f2对b不是D类本身。 (外面)这是非法的。
won't compile, because f2 operates on b not the class D itself. (called outside) It's illegal.
要修复它,B :: f2应该是公开的。
To fix it B::f2 should be public.
这篇关于不能调用基类保护函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!