问题描述
尝试搜索,没有任何返回(我认为).
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
.这是非法的,因为:
Assume std::vector<X>
. This is illegal because:
如果你想用一定数量的元素初始化你的向量,分配就会失败.向量在内部将对象存储在连续内存中.预分配会失败,因为这意味着它需要创建对象,而这对于抽象类是无法完成的.
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.
即使可以,或者基类不是抽象的,也无济于事,因为您会遭受对象切片.
Even if you could, or the base class wasn't abstract, it wouldn't help too much, as you'd suffer from object slicing.
这篇关于制作不同子类实例的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!