将对象添加到向量时编译器错误

Nog*_*oga 2 c++ visual-studio

将对象添加到向量时,为什么会出现以下编译器错误,该向量的数据成员是否引用了另一个对象?

编译错误:

错误1错误C2582:'产品'中的'operator ='功能不可用c:\ program files\microsoft visual studio 8\vc\include\xutility 2726

在程序中,我在创建新的Product对象之前收集所有数据,

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

问题出在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);    
}
Run Code Online (Sandbox Code Playgroud)

来自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;    
} 
Run Code Online (Sandbox Code Playgroud)

Seb*_*anK 6

该对象必须是可分配的(需要operator =)才能与STL容器一起使用.

没有编译器生成的operator =,因为您有一个引用(m_category_ref)作为成员.

  • 没有编译器生成的赋值运算符,因为已声明了非默认构造函数,而不是因为存在引用.引用可以由编译器生成的代码复制,但是其他构造函数禁用默认构造函数和赋值运算符的编译器生成. (3认同)