Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Can';t使用更现代的for循环和派生类对象的向量。为什么?_C++_For Loop_Stdvector - Fatal编程技术网

C++ Can';t使用更现代的for循环和派生类对象的向量。为什么?

C++ Can';t使用更现代的for循环和派生类对象的向量。为什么?,c++,for-loop,stdvector,C++,For Loop,Stdvector,我有一个基类和一些派生类。我生成一些派生类的对象,将其转换为基类,并将它们推送到向量中。我可以使用int索引对向量进行迭代,但不能使用迭代器。知道为什么吗 鉴于 class Product { protected: char product_id; char size_id; public: void Print(); virtual ~Product() = 0; }; class ProductASmall : public Product { public

我有一个基类和一些派生类。我生成一些派生类的对象,将其转换为基类,并将它们推送到向量中。我可以使用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());
…有错误

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 Studio\2019\Community\VC\Tools\MSVC\14.28.29910\include\memory") cannot be referenced -- it is a deleted function   
Error(active)E1776函数“std::unique\u ptr::unique\u ptr(const std::unique\u ptr&)[with _Ty=Product,_Dx=std::default\u delete]”(在“C:\Program Files(x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\include\memory”的第3433行声明)无法引用,它是一个已删除的函数

答案来自@Daniel Langr:


您试图在每次迭代中将一个向量元素复制到p中, 这是不可能的(unique_ptr不支持复制语义)。 简单的解决方法:自动和p,或者更好的,如果足够的话,const自动和p


您试图在每次迭代中将向量元素复制到
p
,这是不可能的(
unique\u ptr
不支持复制语义)。轻松修复:
auto&p
或者,如果足够的话,最好是
const auto&p
。您的评论和链接文章都回答得很好。谢谢我应该删除我的来消除噪音吗?只是自我回答。或者让它保持原样。复制比删除好,因为它能让谷歌向目标公司注入活力
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 Studio\2019\Community\VC\Tools\MSVC\14.28.29910\include\memory") cannot be referenced -- it is a deleted function