2009-11-30 184 views
2

将对象添加到其数据成员正在引用另一个对象的向量时,为什么会出现以下编译器错误?向对象添加对象时发生编译器错误

编译器错误:

错误1个错误C2582: '运算符=' 的功能是在 '产品' C不可用:\程序Files \ Microsoft的Visual Studio 8 \ VC \包括\ xutility 2726

在节目我收集所有数据之前,我创建了一个新的产品对象,

然后,创建对象和所有数据传递给构造函数:

的问题是在的push_back(p)线,

vector<Product> productsArr; 
vector<string> categoriesArr; 

class Product 

{ 

private: 
    string m_code;  
    string m_name;  
    string& m_category_ref;  
    string m_description;  
    double m_price;  
    Product();  
public: 
    Product(const string& code,const string& name,string& refToCategory, 
    const string& description, const double& price):m_category_ref(refToCategory)  
    {  
    m_code = code; 
    m_name = name; 
    m_description = description; 
    m_price = price; 
    } 

} 

void addProduct() 
{  
    string code,name,description;  
    double price;  
    int categoryIndex;  
    getProductData(code,name,price,categoryIndex,description);  
    Product p(code,name,categoriesArr[categoryIndex],description,price);  
    productsArr.push_back(p);  
} 

从xutility行:

// TEMPLATE FUNCTION fill 
template<class _FwdIt, class _Ty> inline 
void __CLRCALL_OR_CDECL _Fill(_FwdIt _First, _FwdIt _Last, const _Ty& _Val) 
{ // copy _Val through [_First, _Last) 
_DEBUG_RANGE(_First, _Last); 
    for (; _First != _Last; ++_First) 
    *_First = _Val;  
} 

回答

6

该对象必须是可分配(需要操作员=)与STL容器一起使用。

没有编译器生成operator =,因为您有一个引用(m_category_ref)作为成员。您添加到STL-集装箱

+3

没有编译器生成的赋值运算符,因为非默认的构造函数已经声明,不是因为有一个参考。引用可以由编译器生成的代码复制,但其他构造函数会禁用默认构造函数和赋值运算符的编译器生成。 – MP24 2009-11-30 13:19:46

+0

@ MP24:对不起,但你错了。编译器应如何实现对引用的分配?他不能,因为现有的不能改变。 没有默认构造函数生成,如果提供了非默认构造函数,也许你的意思是?它与编译器生成的赋值运算符无关。 – SebastianK 2009-11-30 14:56:12

+1

确实。如果要共享“引用”并希望该类可分配,请使用指针成员(如果该类未管理共享对象的内存,则为'std :: tr1 :: shared_ptr')。 – UncleBens 2009-11-30 15:13:54