简体   繁体   中英

Array of inherited object from abstract class C++

I am trying to make an array of different objects that are all inherited from one abstract class. Is this possible? Here's what I have:

Human *human;
human = new Human(100,100);

Cyberdemon *cyberDemon;
cyberDemon = new Cyberdemon(100, 100);

Balrog *balrog; 
balrog = new Balrog(100, 100);

Elf *elf;
elf = new Elf(100, 100);

Human and Elf get inherited from Creature which is an abstract class. Cyberdemon and Balrog get inherited from Demon class which inherits also from Creature. What is the best way to make an array of these four objects?

Because I like code to be tidy:

Human      *human      = new Human(100, 100);
Cyberdemon *cyberDemon = new Cyberdemon(100, 100);
Balrog     *balrog     = new Balrog(100, 100);
Elf        *elf        = new Elf(100, 100);

std::vector<Creature*> creatureList{human, cyberDemon, balrog, elf};

Or, if you won't be needing individual pointers later:

std::vector<Creature*> creatureList{
    new Human(100, 100),
    new Cyberdemon(100, 100),
    new Balrog(100, 100),
    new Elf(100, 100)
};

Or, tidy and safe (thanks Kerrek SB):

std::vector<unique_ptr<Creature>> creatureList{
    std::make_unique<Creature>(100, 100),
    std::make_unique<Cyberdemon>(100, 100),
    std::make_unique<Balrog>(100, 100),
    std::make_unique<Elf>(100, 100)
};
std::vector<Creature*> creatureList;

Human *human;
human = new Human(100,100);
createList.push_back(human);

Cyberdemon *cyberDemon;
cyberDemon = new Cyberdemon(100, 100);
createList.push_back(cyberDemon);

Balrog *balrog; 
balrog = new Balrog(100, 100);
createList.push_back(barlog);

Elf *elf;
elf = new Elf(100, 100);
createList.push_back(elf);

Or, a little bit simplified:

std::vector<Creature*> creatureList;

createList.push_back(new Human(100,100));
createList.push_back(new Cyberdemon(100, 100));
createList.push_back(new Balrog(100, 100));
createList.push_back(new Elf(100, 100));

If you are able to use C++11, you can simplify it a little further (thanks Chnossos).

std::vector<Creature*> creatureList = { new Human(100,100), 
                                        new Cyberdemon(100, 100),
                                        new Balrog(100, 100),
                                        new Elf(100, 100) };

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