【发布时间】:2018-08-20 22:18:18
【问题描述】:
鉴于以下情况:
#include <vector>
struct Widget
{
void doThing()
{
...
}
};
struct SpecialWidget : public Widget
{
void doSpecialThing()
{
...
}
};
int main()
{
std::vector<Widget*> widgets;
widgets.push_back(new Widget());
widgets.push_back(new SpecialWidget());
...
for(auto& w : widgets)
{
w->doThing();
//Also need to call doSpecialThing() if element is a SpecialWidget
}
return 0;
}
在这里将doSpecialThing() 声明为基类Widget 中的虚函数并让它什么都不做是正确的吗?我相当肯定答案是否定的。在哪种情况下,有没有更好的方法来解决这个问题?
亲切的问候
【问题讨论】:
-
你想要
SpecialWidget到doSpecialThing()而不是doThing()?如果是这样,只需覆盖doThing()。如果您想要doSpecialThing()到doThing()和其他东西,请再次覆盖并事先明确调用Widget::doThing()。
标签: c++ inheritance polymorphism