c++ - 从已存储派生类的基类的向量将 unique_ptr 实例化为派生类
问题描述
考虑以下代码:
struct Fruit
{
Fruit() {}
virtual ~Fruit() {}
std::string name;
};
struct Banana : public Fruit
{
std::string color;
};
struct Pineapple : public Fruit
{
int weight;
};
这是我的 main() :
int main()
{
std::vector<std::unique_ptr<Fruit>> product;
product.push_back(std::unique_ptr<Banana>(new Banana)); //product[0] is a Banana
product.emplace_back(new Pineapple);
// I need to acess the "color" member of product[0]
std::unique_ptr<Banana> b = std::move(product[0]); // this doesn't work, why?
auto c = b->color;
}
在product[0]
我将 unique_ptr 存储到 Banana 时,为什么不能将其分配给香蕉 unique_ptr ?
解决方案
您需要显式转换,因为第一个产品可以是任何水果......编译器不知道这个水果是香蕉还是菠萝。
正如@IgorTandetnik 所说,你可以这样做:
std::unique_ptr<Banana> b{static_cast<Banana*>(product[0].release())};
whererelease()
与 一起使用static_cast
。
注意:您不能回退到使用auto
for b,因为编译器会选择struct Fruit
作为类型,以便为任何子类做好准备。
推荐阅读
- apache-kafka - 将数据重新发送给客户端的 Pub-Sub 机制
- git - Git忽略本地更改但将文件推送到远程存储库
- vue.js - 使用 nuxt 组合 api 和 nuxt appollo 模块
- c - 使用 Ascii 字符计数字符
- d3.js - 错误:
属性 d:预期数字,“MNaN,NaNLNaN,NaNZ” - r - 将给定矩阵中所有列的每个“路径”的值相乘
- r - 冲积地块编辑比例和颜色
- php - Laravel - 基于数据透视表状态的数据库查询项目
- php - Laravel 获取有条件的列行数
- amazon-web-services - 如何查看 AWS Personalize 状态更改?