且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们不能声明 std::vector?

更新时间:2022-12-24 09:26:03

你不能实例化抽象类,因此抽象类的向量不能工作.

You can't instantiate abstract classes, thus a vector of abstract classes can't work.

然而,您可以使用指向抽象类的指针向量:

You can however use a vector of pointers to abstract classes:

std::vector<IFunnyInterface*> ifVec;

这也允许你实际使用多态行为——即使类不是抽象的,按值存储也会导致 对象切片.

This also allows you to actually use polymorphic behaviour - even if the class wasn't abstract, storing by value would lead to the problem of object slicing.