为什么我不能在std :: vector中使用抽象类? [英] Why I can not use abstract class in std::vector?

查看:357
本文介绍了为什么我不能在std :: vector中使用抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自那些问题:

  • Why can't we declare a std::vector<AbstractClass>?
  • abstract classes in std containers
  • How to store a vector of objects of an abstract class which are given by std::unique_ptr?

他们都建议我应该改用指针或智能指针.

They all suggested that I should use pointer or smart pointers instead.

据我所知,数据是在std::vector中动态分配的,这意味着std::vector内部存在指针.那么为什么我不能直接使用抽象类呢?为什么我必须对内部使用指针(我指定的指针)才能使用带有std::vector的抽象类.我知道std::vector::resize之类的某些功能将无法使用.但是,std::vector::reservestd::back_inserter将解决此问题.

As far as I know, Data are dynamically allocated in std::vector which means that there are pointers internally in the std::vector. So why I can not use abstract classes directly? why I have to use pointers(The one I specified) for pointers(the internally) in order to use abstract classes with std::vector. I know some features like std::vector::resize won't work. However, std::vector::reserve and std::back_inserter will solve the problem.

推荐答案

据我所知,数据是在std :: vector中动态分配的,这意味着std::vector

那是绝对正确的.但是,指针(实际上是非常常见的实现中的两个指针之一)指向类型为T的大小相同的元素数组,而不是指向T的单个元素或其子类型.本质上,指针用于表示数组,而不是引用类或其子类.

That's absolutely right. However, the pointer (actually, one of two pointers in the very common implementation) points to an array of identically-sized elements of type T, not to a single element of T or its subtype. Essentially, the pointer is used to represent an array, not to refer to a class or its subclass.

这就是为什么您需要额外的间接访问级别的原因-数组T[]的元素在没有 slice切片的情况下不能存储T的子类.

That is why you need an extra level of indirection - elements of an array T[] are not capable of storing subclasses of T without object slicing.

这篇关于为什么我不能在std :: vector中使用抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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