將對象添加到其數據成員正在引用另一個對象的向量時,爲什麼會出現以下編譯器錯誤?向對象添加對象時發生編譯器錯誤
編譯器錯誤:
錯誤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;
}
沒有編譯器生成的賦值運算符,因爲非默認的構造函數已經聲明,不是因爲有一個參考。引用可以由編譯器生成的代碼複製,但其他構造函數會禁用默認構造函數和賦值運算符的編譯器生成。 – MP24 2009-11-30 13:19:46
@ MP24:對不起,但你錯了。編譯器應如何實現對引用的分配?他不能,因爲現有的不能改變。 沒有默認構造函數生成,如果提供了非默認構造函數,也許你的意思是?它與編譯器生成的賦值運算符無關。 – SebastianK 2009-11-30 14:56:12
確實。如果要共享「引用」並希望該類可分配,請使用指針成員(如果該類未管理共享對象的內存,則爲'std :: tr1 :: shared_ptr')。 – UncleBens 2009-11-30 15:13:54