gpt4 book ai didi

c++ - 将对象添加到 vector 时出现编译器错误

转载 作者:搜寻专家 更新时间:2023-10-31 00:05:39 24 4
gpt4 key购买 nike

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

编译错误:

错误 1 ​​error C2582: 'operator =' function is unavailable in 'Product' c:\program files\microsoft visual studio 8\vc\include\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;
}

最佳答案

对象必须是可赋值的(需要 operator=)才能与 STL 容器一起使用。

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

关于c++ - 将对象添加到 vector 时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1819639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com