不能对派生 class 对象的向量使用更现代的 for 循环。为什么?
Can't use more modern for loop with vector of derived class object. Why?
我有一个基础 class 和一些派生的 class。我生成了派生 classes 的一些对象,转换为基础 class,并将它们推入一个向量中。我可以使用 int 索引迭代向量,但不使用迭代器。知道为什么吗?
鉴于...
class Product
{
protected:
char product_id;
char size_id;
public:
void Print();
virtual ~Product() = 0;
};
class ProductASmall : public Product { public: ProductASmall(); };
class ProductAMedium : public Product { public: ProductAMedium(); };
class ProductALarge : public Product { public: ProductALarge(); };
...和...
vector<unique_ptr<Product>> products;
unique_ptr<ProductFactory> product_factory = ProductFactory::GetProductFactory(ProductType::A);
products.push_back(product_factory->CreateSmall());
products.push_back(product_factory->CreateMedium());
products.push_back(product_factory->CreateLarge());
为什么这样做...
for (unsigned int i = 0; i < products.size(); i++)
{
products[i]->Print();
}
...这失败了...
for (auto p : products)
{
p->Print();
}
...有错误...
Error (active) E1776 function "std::unique_ptr<_Ty, _Dx>::unique_ptr(const std::unique_ptr<_Ty, _Dx> &) [with _Ty=Product, _Dx=std::default_delete<Product>]" (declared at line 3433 of "C:\Program Files (x86)\Microsoft Visual Studio19\Community\VC\Tools\MSVC.28.29910\include\memory") cannot be referenced -- it is a deleted function
答案来自@Daniel Langr:
You are trying to copy a vector element into p in each iteration,
which is not possible (unique_ptr doesn't support copy semantics).
Easy fix: auto & p or, better if sufficient, const auto & p.
我有一个基础 class 和一些派生的 class。我生成了派生 classes 的一些对象,转换为基础 class,并将它们推入一个向量中。我可以使用 int 索引迭代向量,但不使用迭代器。知道为什么吗?
鉴于...
class Product
{
protected:
char product_id;
char size_id;
public:
void Print();
virtual ~Product() = 0;
};
class ProductASmall : public Product { public: ProductASmall(); };
class ProductAMedium : public Product { public: ProductAMedium(); };
class ProductALarge : public Product { public: ProductALarge(); };
...和...
vector<unique_ptr<Product>> products;
unique_ptr<ProductFactory> product_factory = ProductFactory::GetProductFactory(ProductType::A);
products.push_back(product_factory->CreateSmall());
products.push_back(product_factory->CreateMedium());
products.push_back(product_factory->CreateLarge());
为什么这样做...
for (unsigned int i = 0; i < products.size(); i++)
{
products[i]->Print();
}
...这失败了...
for (auto p : products)
{
p->Print();
}
...有错误...
Error (active) E1776 function "std::unique_ptr<_Ty, _Dx>::unique_ptr(const std::unique_ptr<_Ty, _Dx> &) [with _Ty=Product, _Dx=std::default_delete<Product>]" (declared at line 3433 of "C:\Program Files (x86)\Microsoft Visual Studio19\Community\VC\Tools\MSVC.28.29910\include\memory") cannot be referenced -- it is a deleted function
答案来自@Daniel Langr:
You are trying to copy a vector element into p in each iteration, which is not possible (unique_ptr doesn't support copy semantics). Easy fix: auto & p or, better if sufficient, const auto & p.