derived class 的虚函数调用 base class 的虚函数

Virtual function of derived class calls that of base class

#include <iostream>
using namespace std;
class Widget {
public:
    int width;
    virtual void resize() { width = 10; }
};
class SpeWidget :public Widget {
public:
    int height;
    void resize() override {
        //Widget::resize();
        Widget* th = static_cast<Widget*>(this);
        th->resize();
        height = 11;
    }
};
int main() {
    //Widget* w = new Widget;
    //w->resize();
    //std::cout << w->width << std::endl;
    SpeWidget* s = new SpeWidget;
    s->resize();
    std::cout << s->height << "," << s->width << std::endl;
    std::cin.get();
}

Derived class (SpeWidget) 虚函数 (resize()) 想要在基础 class (Widget) 中调用它。为什么上面的代码会出现段错误。谢谢!

注释掉的代码是对的

Widget::resize();

您的替代代码有误。

Widget* th = static_cast<Widget*>(this);
th->resize();

想一想:您正在通过 指向基 class 的指针调用虚函数。当您使用任何虚函数执行此操作时会发生什么?它调用最派生的版本。换句话说,无限递归。