[英]emplace_back and Inheritance
I am wondering if you can store items into a vector, using the emplace_back, a type that is derived from the class that vector expects. 我想知道是否可以使用emplace_back(一种从vector期望的类派生的类型)将项目存储到vector中。
For example: 例如:
struct fruit
{
std::string name;
std::string color;
};
struct apple : fruit
{
apple() : fruit("Apple", "Red") { }
};
Somewhere else: 别的地方:
std::vector<fruit> fruits;
I want to store an object of type apple inside the vector. 我想在向量中存储一个apple类型的对象。 Is this possible?
这可能吗?
No. A vector only stores elements of a fixed type. 否。向量仅存储固定类型的元素。 You want a pointer to an object:
您需要一个指向对象的指针:
#include <memory>
#include <vector>
typedef std::vector<std::unique_ptr<fruit>> fruit_vector;
fruit_vector fruits;
fruits.emplace_back(new apple);
fruits.emplace_back(new lemon);
fruits.emplace_back(new berry);
std::vector<fruit> fruits;
It only stores fruit in fruits not derived types as allocator only allocates sizeof(fruit)
for each element. 它仅将水果存储在非派生类型的水果中,因为分配器仅为每个元素分配
sizeof(fruit)
。 To keep polymorphism, you need to store pointer in fruits. 为了保持多态性,您需要将指针存储在水果中。
std::vector<std::unique_ptr<fruit>> fruits;
fruits.emplace_back(new apple);
apple is dynamically allocated on free store, will be release when element is erased from vector. 苹果是在免费商店中动态分配的,当从向量中删除元素时,它将被释放。
fruits.erase(fruits.begin());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.