为什么在私有继承下覆盖?

时间:2016-08-19 08:29:40

标签: c++ c++11

class Base {
public:
   virtual void f() {}
};

class Derived : private Base {
public:
   void f() override {}
};

我的问题是这样的覆盖是否有用?私有继承意味着您无法将Derived存储在Base指针中,因此永远不需要将f动态分派到正确的类型。

1 个答案:

答案 0 :(得分:7)

仅举一个例子:Derived::f1()的函数可以调用Base::f2()的(公共或受保护)函数,而这些函数又可以调用f()。在这种情况下,需要动态调度。

以下是一个示例代码:

#include "iostream"
using namespace std;

class Base {
  public:
    virtual void f()  { 
      cout << "Base::f() called.\n"; 
    }
    void f2() { 
      f(); // Here, a dynamic dispatch is done!
    }
};

class Derived:private Base {
  public:
    void f() override { 
      cout << "Derived::f() called.\n"; 
    }
    void f1() { 
      Base::f2(); 
    }
};

int main() {
  Derived D;
  D.f1();
  Base    B;
  B.f2();
}

输出:

Derived::f() called
Base::f() called