创建不同子类的实例的向量 [英] Making a vector of instances of different subclasses

查看:201
本文介绍了创建不同子类的实例的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试搜索,没有返回(i ithink)。

Tried searching, nothing returns( i ithink).

是否可以创建抽象类的向量?

Is it possible to make a vector of an abstract class?

例如,我有超级类Unit。

For example, I have the super class Unit.

我有子类兵士,车辆和轰炸机。

And I Have the subclasses soldier, vehicle, and bomber.

然而,我想要任何子类的一个向量中的实例,例如向量UnitList可以持有士兵和车辆的实例?

However I would want ever instance of any subclass in one vector, e.g. the vector UnitList can hold instances of both soldier and vehicle?

这是可能吗?
我使用C ++如果它有帮助。

Is this possible? I'm using C++ if it helps.

推荐答案

是的,但你需要使用指针或智能指针(我会用这个)。

Yes, but you'll need to use either pointers or smart pointers (I'd go with this).

struct X
{
    virtual ~X() {}  //<--- as pointed out in the comments
                     // a virtual destructor is required
                     // for correct deletion
    virtual void foo() = 0;
};
struct Y : X
{
    virtual void foo() { }
};

int main()
{
    std::vector<X*> a;
    a.push_back(new Y);
    a[0]->foo();
    for ( int i = 0 ; i < a.size() ; i++ )
        delete a[i];
    return 0;
}

不要忘记删除已分配的内存。

Don't forget to delete the allocated memory.

假设 std :: vector< X> 。这是非法的,因为:

Assume std::vector<X>. This is illegal because:


  1. 如果你想用一些元素初始化你的向量,向量在连续内存中内部存储对象。

  1. If you want to initialize your vector with some number of elements, the allocation would fail. A vector stores objects internally in continuous memory. A preallocation would fail because it would mean it needed to create objects, which can't be done for abstract classes.

即使你可以,或者基础

这篇关于创建不同子类的实例的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆