【发布时间】:2020-07-10 01:43:06
【问题描述】:
#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();
}
派生类 (SpeWidget) 虚函数 (resize()) 想在基类 (Widget) 中调用它。为什么上面的代码有段错误。谢谢!
【问题讨论】:
-
见:Can I call a base class's virtual function if I'm overriding it?。因为
resize是virtual,即使你通过Widget*调用它,它也会从派生类SpeWidget调用“正确”函数。从超类调用方法的正确语法是Widget::resize()。也就是说,你可以写void resize() override { Widget::resize(); height = 11; },或者void resize() override { this->Widget::resize(); height = 11; },如果你愿意的话。 -
this->Widget::resize()解释清楚,我想。
标签: c++ virtual-functions