[英]emplace_back and Inheritance
我想知道是否可以使用emplace_back(一種從vector期望的類派生的類型)將項目存儲到vector中。
例如:
struct fruit
{
std::string name;
std::string color;
};
struct apple : fruit
{
apple() : fruit("Apple", "Red") { }
};
別的地方:
std::vector<fruit> fruits;
我想在向量中存儲一個apple類型的對象。 這可能嗎?
否。向量僅存儲固定類型的元素。 您需要一個指向對象的指針:
#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);
std::vector<fruit> fruits;
它僅將水果存儲在非派生類型的水果中,因為分配器僅為每個元素分配sizeof(fruit)
。 為了保持多態性,您需要將指針存儲在水果中。
std::vector<std::unique_ptr<fruit>> fruits;
fruits.emplace_back(new apple);
蘋果是在免費商店中動態分配的,當從向量中刪除元素時,它將被釋放。
fruits.erase(fruits.begin());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.