C++ 在派生自基 class 中调用覆盖的函数

C++ Calling overwritten function in derived from base class

我有 2 个 类、AB,我需要 B 中的一个覆盖函数,以便从 A 的构造函数中调用。这是我已经拥有的:

class A {
    A(char* str) {
        this->foo();
    }

    virtual void foo(){}
}

class B : public A {
    B(char* str) : A(str) {}

    void foo(){
        //stuff here isn't being called
    }
}

如何从 A::A() 获取要在 B::foo() 中调用的代码?

我认为您指的是在初始化过程中调用虚拟(也称为初始化过程中的动态绑定),所以请看这里,其中解释了所有内容:

  1. https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Calling_Virtuals_During_Initialization
  2. https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctor-idiom

第二个站点有很好的解释,但比第一个站点长得多。

在构造函数中,将调用基础 class' 函数,而不是重写版本。这样做的原因是,使用您的示例,在调用 A 的构造函数时 B 的初始化未完成,因此调用 Bfoo 将如果允许,则使用不完整的 B 实例完成。

I need an overwritten function in B to be called from A's constructor

这种设计在C++中是不可能的:B对象的order of construction是先构造基础A子对象,然后在其上构造B。

结果是,在A构造函数中,你仍然在构造一个A对象:此时调用的任何虚函数都是A的虚函数。只有当A构造完成,B构造开始时, B的虚函数会不会生效。

为了实现您想要的效果,您必须使用两步模式:1) 构造对象,2) 初始化它。