我的问题用更长的继承链扩展了这个问题
这是我的代码:
////////// View ///////////////
class View{
public:
void Render(){
std::cout << "View::Render" << std::endl;
render();
}
protected:
virtual void render() = 0;
};
////////// ImageView ///////////////
class ImageView : public View{
public:
protected:
void render(){
std::cout << "ImageView:render" << std::endl;
}
};
////////// Sprite ///////////////
class Sprite : public ImageView{
public:
protected:
void render(){
std::cout << "Sprite:render" << std::endl;
}
};
////////// Utility ///////////////
void Draw(View *vw){
vw->Render();
}
////////// main ///////////////
int main(){
std::cout << "... Draw ImageView ..." << std::endl;
ImageView *imgvw = new ImageView;
Draw(imgvw);
delete imgvw;
std::cout << "... Draw Sprite ..." << std::endl;
Sprite *sp = new Sprite;
Draw(sp);
delete sp;
return 0;
}
实际输出:
.. Draw ImageView ...
View::Render
ImageView:render
... Draw Sprite ...
View::Render
Sprite:render
所需输出:
.. Draw ImageView ...
View::Render
ImageView:render
... Draw Sprite ...
View::Render
ImageView:render
Sprite:render
我试图只保留一个应该调用所有虚拟方法链的基类公共方法。在 C++ 中这样的事情可能吗?