创建多个对象的链接列表

时间:2015-06-03 14:12:12

标签: c++ list

我需要帮助,如果我有:

class gameObject{
    public: //get and set;
    private: int x;
    int y;
    string texture;
}

class gun:public gameObject{
    public: //get and set;
    private: int ammo;
}

class armor:public gameObject ... ,
class boots:public gameObject...

如何从基类gameObject创建多个派生对象的链表?例如,用户有一个菜单:[1。添加对象2.删除对象]。如果用户选择1,则出现另一个菜单[类型:1-Gun 2-Armor]。添加4个对象后,列表将是:1.Gun 2.Armor 3.Gun 4.Boots。 我需要一个例子来理解这个概念。

感谢。

3 个答案:

答案 0 :(得分:1)

  

如何从基类gameObject创建多个派生对象的链表?

您可以将std::forward_list(单链表)或std::list(双向链表)与智能指针std::unique_ptrstd::shared_ptr结合使用(取决于拥有的语义) ),如下所示:

std::list<std::unique_ptr<gameObject>> list;

然后你将使用:

分配对象
list.emplace_back(std::make_unique<gameObject>(...));

答案 1 :(得分:1)

其他人的答案很好,但如果他们在这里回答错误的问题:

指向基类型(智能或其他)的指针也可以指向任何派生类型,因此您需要创建指向基类型的指针列表。

您无法列出基本类型本身,因为派生类型可能更大且不适合。这种语言甚至不会让你尝试。

std::list<GameObject *> is ok.
std::list<GameObject> is not.

答案 2 :(得分:0)

你会想要使用自动指针。

list<unique_ptr<gameObject>> foo;

foo.push_back(make_unique<gun>());
foo.push_back(make_unique<armor>());

for(auto& i : foo){
    if(dynamic_cast<gun*>(i.get())){
        cout << "gun" << endl;
    }else if(dynamic_cast<armor*>(i.get())){
        cout << "armor" << endl;
    }
}

此示例将gunarmor添加到foo作为unique_ptr<gameObject>

for - 循环中,我们使用dynamic_cast来识别类型。代码将输出:

  


  装甲

您可以在此处查看此代码的示例:http://ideone.com/trj9bn

相关问题