我正在尝试制作一个全部继承基类的 GUI 元素系统。我希望能够通过调用父类中的 Draw 方法来调用所有子元素。这基本上是我到目前为止所拥有的:
基本元素:
interface GuiElementBase
{
protected:
std::vector<GuiElementBase> children;
public:
void Draw()
{
for (int i = 0; i < children.size(); i++)
children[i].Draw();
}
void AddChild(GuiElementBase child)
{
children.push_back(child);
}
};
文本元素:
class GuiElementText : public GuiElementBase
{
public:
void Draw()
{
GuiElementBase::Draw();
// + some text-specific drawing code
}
};
实现:
GuiElementText* TextTest;
void GUI::Init()
{
TextTest = new GuiElementText();
TextTest->AddChild(GuiElementText());
}
void GUI::Draw()
{
TextTest->Draw();
}
为简单起见,省略了构造函数、绘图代码和其他方法。
当它尝试更新 TextTest 子项时,它显然只是调用 GuiElementBase::Draw(),因为“子项” vector 是 GuiElementBase。我一直无法找到一种方法让它调用子对象而不是基类。非常感谢所有帮助!
最佳答案
在以下示例中,首先执行基础 Draw(),然后为 vector 中的每个子级执行 Draw()。这就是你想要的吗?
#include <iostream>
class GuiElementBase
{
private:
std::vector<GuiElementBase *> children;
public:
virtual void Draw()
{
std::cout << "GuiElementBase draw" << std::endl;
for (int i = 0; i < children.size(); i++)
children[i]->Draw();
}
void AddChild(GuiElementBase *child)
{
children.push_back(child);
}
};
class GuiElementText : public GuiElementBase
{
public:
void Draw() override
{
std::cout << "GuiElementText draw" << std::endl;
}
};
int main()
{
GuiElementBase base;
GuiElementText* child = new GuiElementText();
base.AddChild(child);
base.AddChild(child);
base.Draw();
return 0;
}
打印:
GuiElementBase draw
GuiElementText draw
GuiElementText draw
关于c++ - 调用列表中子对象方法的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47297830/