简体   繁体   English

来自抽象类C ++的继承对象的数组

[英]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. 人和精灵都继承自Creature,后者是一个抽象类。 Cyberdemon and Balrog get inherited from Demon class which inherits also from Creature. Cyber​​demon和Balrog继承自Demon类,该类也继承自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): 或者,整洁又安全(感谢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). 如果您能够使用C ++ 11,则可以进一步简化它(感谢Chnossos)。

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

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

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