2012-09-01 23 views
0

我很抱歉,但不能有一個例子,所以我們不得不在這裏看看真實的代碼。 會發生什麼事情,我有類CItemElem(請注意,這是一箇舊的來源,請不要重視匈牙利符號,類名等)。 作爲在下面的例子中我試圖做同樣的CItemElem爲什麼插入一個對象到向量導致C2679

class A 
{ 
public: 
    int value; 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    std::vector<A> hold; 
    A a; 
    hold.push_back(a); 
} 

Althought與CItemElem類試圖通過

vector<CItemElem>hold; CItemElem item; hold.push_back(item);

Error C2679: '=' binary :no operator found which takes a right-hand operand of type 'const CItemElem' (or there is no acceptable conversion)

當編譯器給我C2679點擊錯誤,它導致我在這條線*_First = _Val; 在此功能xutility

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

的CItemElem類過長和派生,所以我決定,而不是在這裏粘貼代碼,龐大將其上傳到引擎收錄。 Pastebin: Class CItemElem Header (item.h)

請注意,CItemElem從CItemBase派生而來,並具有=運算符重載,它也通過CItemBase =運算符。這是item.cpp

CItemElem& CItemElem::operator =(CItemElem & ie) 
{ 
    CItemBase::operator =(ie); 
+0

當然,您可以將「CItemElem」的定義修剪爲可以在此處發佈的較小的東西。這裏有個提示:編譯器在抱怨賦值運算符;幾乎所有的東西都是無關緊要的。 –

+0

是的,CItemElem是CItemBase的派生類,'operator ='被重載,'virtual'重載,這意味着CItemBase也會參與=操作。問題是如何解決這個問題 –

回答

3

對於CItemElem,看起來好像沒有定義的賦值運算符(=)。 STL容器(例如vector)希望它們包含的內容具有某些屬性,包括賦值運算符。如果你可以修改類,你可以添加一個:

class CItemElem 
{ 
... 
public: 

    CItemElem & operator=(const CItemElem &other) 
    { 
    // copy whatever must be copied 
    x = other.x; 

    return *this; 
    } 
} 

編輯:
我現在看到標題包括賦值運算符的聲明:

virtual CItemElem&  operator = (CItemElem & ie); 

但簽名錯 - 它丟失const。如果你可以改變它(在聲明和定義中),它應該起作用。

編輯:
如果你不能編輯基類,你有幾個選項。可能最安全的是將代碼從CItemBase::operator=複製到CItemElem::operator=。這不太好,但那是原作者的錯。這個論據一直應該是const &

+0

謝謝!是的,這是真正的答案,可以使用CItemElem和向量,我只需在簽名處添加'const'!專家的眼睛,我很驚訝! –

2

CItemElem有operator=(CItemElem&)。此函數不能接受const參數(如編譯器準確告訴您的)並且不符合std::vector作爲元素類型的要求。在std::vector中使用這個類是不可能的。

相關問題