emplace_back和继承 [英] emplace_back and Inheritance

查看:85
本文介绍了emplace_back和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用emplace_back(一种从vector期望的类派生的类型)将项目存储到vector中。

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.

例如:

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

struct apple : fruit
{
    apple() : fruit("Apple", "Red") { }
};

其他地方:

std::vector<fruit> fruits;

我想在矢量内部存储一个apple类型的对象。

I want to store an object of type apple inside the vector. 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);

这篇关于emplace_back和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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