emplace_back和继承

The*_*eAJ 4 c++ inheritance vector c++11

我想知道你是否可以使用emplace_back将项目存储到一个向量中,这是一种从向量所期望的类派生的类型.

例如:

struct fruit
{
    std::string name;
    std::string color;
};

struct apple : fruit
{
    apple() : fruit("Apple", "Red") { }
};
Run Code Online (Sandbox Code Playgroud)

别的地方:

std::vector<fruit> fruits;
Run Code Online (Sandbox Code Playgroud)

我想在向量中存储apple类型的对象.这可能吗?

Ker*_* SB 9

不可以.矢量只存储固定类型的元素.你想要一个指向对象的指针:

#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);
Run Code Online (Sandbox Code Playgroud)

  • @TheAJ:嗯,这就是重点,对吧?如果要保留对象,请将指针传输到容器... (2认同)