调用私有非虚拟 Base class 函数而不是 Derived class 中的函数

Private non-virtual Base class function is called instead of the one in Derived class

class Base{
public:
    void callF(){ F(); }
private:
    void F(){}
};
class Derived: public Base{
public:
    void F(){}
};
int main(){
    Derived d;
    d.callF();
}

令我惊讶的是,Base F() 被调用了。我不明白为什么。 F()在Baseclass中被声明和定义为private,所以Derived对象甚至不知道Base中有这样一个函数。 Derived class 有自己的 F(),但该函数被忽略了。问题是"Why is the Base class F() called? ".

我不确定这是否回答了您的问题

The question is "Why is the Base class F() called? ".

那是因为派生的类中只能覆盖virtual函数(动态多态1),除非你使用 CRTP (静态多态性1):

template<class Derived>
class Base{
public:
    void callF(){ static_cast<Derived*>(this)->F(); }
private:
    void F(){}
};
class Derived: public Base<Derived>{
public:
    void F(){}
};

否则

    void callF(){ F(); }

相当于

    void callF(){ Base::F(); }

1)另见 What is the difference between compile time polymorphism and static binding?

事情是这样的。

  1. 调用了Base::callF函数。它是 public 所以从 main.
  2. 调用它没有问题
  3. Base::callF 函数想要调用名为 F 的函数。 Base::callF 可见的唯一 FBase::F。它是私有的,但 callFBase 的成员,因此它可以查看和使用所有其他成员,包括私有成员。
  4. Derived::F函数与这些无关。它只是另一个函数,与 Base::F 无关,恰好具有相似的名称。