友善和派生阶级

ere*_*eOn 2 c++ inheritance compiler-errors friend

假设我有以下类层次结构:

class Base
{
  protected:

    virtual void foo() = 0;

    friend class Other;
};

class Derived : public Base
{
  protected:

    void foo() { /* Some implementation */ };
};

class Other
{
  public:

    void bar()
    {
      Derived* a = new Derived();

      a->foo(); // Compiler error: foo() is protected within this context
    };
};
Run Code Online (Sandbox Code Playgroud)

我想我也可以改变它a->Base::foo()但是因为foo()Base课堂上是纯粹的虚拟,所以Derived::foo()无论如何呼叫都将导致呼叫.

但是,编译器似乎拒绝了a->foo().我想这是合乎逻辑的,但我不能理解为什么.我错过了什么吗?不能(不应该)它处理这种特殊情况?

谢谢.

Tyl*_*nry 6

使用类名限定方法名称时,如在Base::foo()动态分派(运行时绑定)中不适用.它总是会调用Base实现foo(),无论是否foo()为虚拟.因为在这种情况下它是纯虚拟的,所以没有实现,编译器会抱怨.

你的第二个问题是在C++中,友谊不是继承的.如果您想要Other特殊访问权限Derived,则需要成为Derived具体的朋友.

另一方面,这有效:

Base* a = new Derived();

a->foo(); 
Run Code Online (Sandbox Code Playgroud)

因为在这里,你呼吁foo()Base*这里foo()是公开的,因为你没有资格foo()与类的名字,它使用动态调度和结束呼叫Derived的版本Foo.