我試圖創建一個將數組中的Movie
對象存儲的泛型類。 我想覆蓋+=
和-=
運算符以添加或刪除數組中的元素。錯誤C2677:binary'+ =':找不到需要輸入'Movie'的全局運算符(或者沒有可接受的轉換)
template<typename Element>
movieArray<Element>& movieArray<Element>::operator-=(int position)
{
// some code here...
return *this;
}
template<typename Element>
void movieArray<Element>::deleteElem(int position)
{
this->elements -= position;
}
刪除部分按預期工作。然而,當我做添加操作同樣的事情:
template<typename Element>
movieArray<Element>& movieArray<Element>::operator+=(const Element &elem)
{
elements[lenght++] = elem;
return *this;
}
template<typename Element>
void movieArray<Element>::addElem(const Element &elem)
{
resizeArray();
this->elements += elem;
}
我收到以下錯誤:
error C2677: binary '+=' : no global operator found which takes type 'Movie' (or there is no acceptable conversion)
我不知道爲什麼會這樣。
如果我改變Element
到int
,就像我在-=
方法,代碼編譯。
你需要改變你的標題,以更好地反映實際問題,而不是一個非常具體的錯誤。否則你不會得到太多的迴應。例如:指定二進制+ =全局運算符時出錯。 – CaptainBli
你能展示你實例化你的模板的代碼片段嗎? – Christophe
元素聲明爲什麼?錯誤是告訴你用於'elements'的類型沒有'operator + ='實現,它接受一個'Movie'作爲輸入。如果你想用'addElem()'來調用你的'operator + =',那麼使用'* this + = elem;'而不是'this-> elements + = elem;'與'deleteElem()'類似,來調用''operator - =',使用'* this - = position;'而不是'this-> elements - = position;'。 –