emplace_back and Inheritance

蓝咒 提交于 2020-01-23 08:18:04

问题


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.

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. Is this possible?


回答1:


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);



回答2:


std::vector<fruit> fruits; It only stores fruit in fruits not derived types as allocator only allocates sizeof(fruit) for each element. 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());


来源:https://stackoverflow.com/questions/14420826/emplace-back-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!