gpt4 book ai didi

c++ - 强制沿长链调用基类虚函数

转载 作者:行者123 更新时间:2023-11-27 23:14:37 26 4
gpt4 key购买 nike

我的问题扩展了 this problem具有更长的继承链

这是我的代码:

////////// 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

我试图只保留一个应该调用所有虚拟方法链的基类公共(public)方法。在 C++ 中可以实现这样的功能吗?

最佳答案

根据 this question (Can I call a base class's virtual function if I'm overriding it?) ,像这样改变你的定义:

class Sprite : public ImageView{
public:
protected:
void render(){
ImageView::render(); // this calls the superclass' virtual method
std::cout << "Sprite:render" << std::endl;
}
};

关于c++ - 强制沿长链调用基类虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com