简体   繁体   English

创建多个对象的链接列表

[英]Create linked list of multiple objects

I need help, if I have: 我需要帮助,如果有:

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

How I can create a linked list of multiple derived objects from base class gameObject ? 如何从基类gameObject创建多个派生对象的链接列表? For example user have a menu: [1. 例如,用户有一个菜单:[1。 Add object 2.Delete object]. 添加对象2.删除对象]。 If user choose 1 another menu appear [Type: 1-Gun 2-Armor]. 如果用户选择1,则出现另一个菜单[类型:1-Gun 2-Armor]。 After 4 objects added the list will be: 1.Gun 2.Armor 3.Gun 4.Boots. 添加4个对象后,列表将为:1.Gun 2.Armor 3.Gun 4.Boots。 I need an example to understand the concept. 我需要一个例子来理解这个概念。

Thanks. 谢谢。

How I can create a linked list of multiple derived objects from base class gameObject ? 如何从基类gameObject创建多个派生对象的链接列表?

You would use std::forward_list (singly linked list) or std::list (doubly linked list) in conjunction with a smart pointer like std::unique_ptr or std::shared_ptr (depending on owning semantic), as demonstrated below: 您可以将std::forward_list (单链表)或std::list (双链表)与智能指针(如std::unique_ptrstd::shared_ptr (取决于拥有的语义))结合使用,如下所示:

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

and then you would allocate objects using: 然后您将使用以下方法分配对象:

list.emplace_back(std::make_unique<gameObject>(...));

Other peoples answers were good, but in case they were answering the wrong question here: 其他人的回答很好,但是如果他们在这里回答了错误的问题:

A pointer to the base type (smart or otherwise) can point to any of the derived types too, so you need to make a list of pointers to the base type. 指向基本类型的指针(智能或其他)也可以指向任何派生类型,因此您需要列出指向该基本类型的指针。

You can't make a list of the base type itself, because the derived types are probably bigger and wouldn't fit. 您无法列出基本类型本身,因为派生类型可能更大并且不合适。 The language won't even let you try. 该语言甚至不会让您尝试。

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

You'll want to use auto pointers for this. 您将为此使用自动指针。

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;
    }
}

This example adds a gun and then an armor to foo as unique_ptr<gameObject> s. 此示例在foo添加了gunarmor ,作为unique_ptr<gameObject>

In the for -loop we use a dynamic_cast to discern the type. for循环中,我们使用dynamic_cast来识别类型。 The code will output: 该代码将输出:

gun
armor 盔甲

You can see an example of this code here: http://ideone.com/trj9bn 您可以在此处查看此代码的示例: http : //ideone.com/trj9bn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM