c++ - 调用列表中子对象方法的最佳方法?

标签 c++

我正在尝试制作一个全部继承基类的 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/

相关文章:

c++ - 在 C 和 C++ 中通过编译器环境变量或命令行标志指定库路径?

c++ - enable_if 模板特化自定义特征

c++ - 声明一些未知精度的 vector

c++ - Win XP x64 上的段错误在 XP x32 上不会发生 - strncpy 问题?怎么修?

c++ - Tcpdump - pcap - 无法嗅探端口 5984 上的数据包

c++ - 错误 : no operator "<" matches these operands

c++ - 如何根据排序索引 vector 对 std::set 索引进行排序?

c++ - 编写计算 nCr 值的程序 (C++)

c++ - Boost/Python 有 make_array 方法吗?

c++ - 在 Qt 中缩放图形