Consider following piece of code:
struct Fruit
{
Fruit() {}
virtual ~Fruit() {}
std::string name;
};
struct Banana : public Fruit
{
std::string color;
};
struct Pineapple : public Fruit
{
int weight;
};
这是我的主函数:
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]
中,我存储了一个指向Banana的unique_ptr,为什么不能将它分配给一个banana unique_ptr?
product[0]
指向的是Banana
而不是其他Fruit
。如果你确定它指向Banana
,你可以通过强制类型转换告诉编译器。例如:std::unique_ptr<Banana> b{static_cast<Banana*>(product[0].release())};
- Igor Tandetnikstd::unique_ptr<Banana> b = std::move(product[0]);
也会出现类似的问题,因此我认为这就是你想要的。如果你不想从向量中取得所有权,请使用auto b = static_cast<Banana*>(product[0].get());
。 - Igor Tandetnik