gpt4 book ai didi

c++ - emplace_back 和继承

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:53 26 4
gpt4 key购买 nike

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

例如:

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

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

其他地方:

std::vector<fruit> fruits;

我想在 vector 中存储一个 apple 类型的对象。这可能吗?

最佳答案

没有。 vector 仅存储固定类型的元素。你想要一个指向对象的指针:

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

关于c++ - emplace_back 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com