데이터 멤버가 다른 개체를 참조하고있는 벡터에 개체를 추가 할 때 다음 컴파일러 오류가 발생하는 이유는 무엇입니까? 벡터에 개체를 추가 할 때 컴파일러 오류가 발생했습니다.
컴파일러 에러 :오류 1 오류 C2582 '연산자 ='기능 '제품'C에 사용할 수는 : \ 프로그램 파일은 마이크로 소프트 비주얼 스튜디오 8 \ 벤처 \를 \ \ xutility 2,726
하여 포함 나는 새로운 제품 객체를 생성하기 전에 모든 데이터를 수집하는 프로그램, 다음
, 객체를 생성하고 생성자에 모든 데이터를 전달 :
문제가와 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
@ MP24 : 죄송합니다.하지만 틀렸어요. 컴파일러는 참조에 대한 할당을 어떻게 구현해야합니까? 그는 존재를 바꿀 수 없기 때문에 그는 할 수 없습니다. 기본값이 아닌 생성자가 제공되지 않으면 생성자가 생성되지 않습니다. 컴파일러가 생성 한 대입 연산자와 아무런 관련이 없습니다. – SebastianK
실제로. "참조"를 공유하고 클래스를 할당 가능하게하려면 포인터 멤버를 사용하십시오 (클래스가 공유 객체의 메모리를 관리하지 않으면, 그렇지 않으면'std :: tr1 :: shared_ptr'). – UncleBens