2017-11-15 4 views
3

私はすべての基本クラスを継承する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であるため、明らかにGuiElementBase :: Draw()を呼び出すだけです。私は、基本クラスではなく子オブジェクトを呼び出す方法を見つけるのが難しいです。すべての助けが大変ありがとう!

+1

'interface'は何ですか? –

+1

@AluanHaddad構造体 – hkva

+1

マクロの代わりに純粋な抽象クラスを使用するか、それが何であっても使用する必要があります。 –

答えて

0

次の例では、ベースのDraw()が最初に実行され、次にベクトルの各子に対して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 
+0

ええ、なぜ私は仮想機能が存在するのを完全に忘れたのか分かりません。ありがとう。 – hkva

関連する問題