简体   繁体   中英

How can I have several inherited classes together in the same array?

I have a few classes, ObjDef , PeopDef , NpcDef , and PlyDef , such that PlyDef and NpcDef each seperately inherit PeopDef , and PeopDef inherits ObjDef. Each class has functionality that builds on the class before it, so it's important that PeopDef::Tick is called before ObjDef::Tick . I have every object stored in a vector<ObjDef> object , but when the main tick loop goes through them, I want them to call the original classes' Tick, rather than ObjDef::Tick , which is what the vector<ObjDef> currently makes it do. Is there any way to do this, or do I have to have a separate vector for each class?

You can store an ObjDef pointer (ObjDef* or a smart pointer) in the vector and make the Tick method virtual.

Here's an example:

#include <iostream>
#include <vector>
#include <memory>

class ObjDef
{
public:
    virtual void Tick()
    {
        std::cout << "ObjDef::Tick\n";
    }
};

class PeopDef : public ObjDef
{
public:
    virtual void Tick()
    {
        std::cout << "PeopDef::Tick\n";
    }
};

int main()
{
    std::vector<std::shared_ptr<ObjDef>> objects;

    std::shared_ptr<ObjDef> obj(new ObjDef());
    std::shared_ptr<ObjDef> peop(new PeopDef());

    objects.push_back(obj);
    objects.push_back(peop);

    for (auto object : objects)
    {
        object->Tick();
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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