抽象类C ++中的继承对象数组

时间:2014-05-01 16:43:40

标签: c++ arrays inheritance

我正在尝试创建一个从一个抽象类继承的不同对象的数组。这可能吗?这就是我所拥有的:

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和Elf继承自作为抽象类的Creature。 Cyber​​demon和Balrog从继承自Creature的Demon类继承而来。制作这四个对象数组的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

因为我喜欢整洁的代码:

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

或者,如果您以后不再需要单独的指针:

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

或者,整洁安全(感谢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)
};

答案 1 :(得分:3)

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

或者,稍微简化一下:

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

如果你能够使用C ++ 11,你可以进一步简化它(感谢Chnossos)。

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