2014-01-24 22 views
2

我發現了很多有關此錯誤的討論,但是我沒有嘗試過迄今爲止所做過的工作。我試圖重載「+」運算符,它只適用於2個加數(v3 = v1 + v2),當我嘗試3個加數(v4)時= v1 + v2 + v3),它返回最後一個加數(v3)。我發現這是因爲當第二次調用重載+運算符的函數時,第一個加數的指針的值爲0xcccccccc。這意味着它可能對不再存在的東西產生影響。但是,我不知道如何從超載函數返回矢量對象。這是我曾經嘗試過,但這些作品:返回帶有重載操作符的不可訪問地址的指針+

//this works only for two addends 
template <class T> Vector<T>& operator+(Vector<T>& v1, Vector<T>& v2) 
{ 
    Vector<T> v; 
    //calculations 
    return v; 
}; 

//this causes above mentioned error 
template <class T> Vector<T> operator+(Vector<T>& v1, Vector<T>& v2) 
{ 
    Vector<T> v; 
    //calculations 
    return v; 
}; 

//this causes above mentioned error too 
template <class T> Vector<T> operator+(Vector<T>& v1, Vector<T>& v2) 
{ 
    Vector<T>* v= new Vector<T>; 
    //calculations 
    return (*v); 
}; 

不知道如何返回矢量對象,因此它將與3個加數工作呢?

+1

第一個版本總是被破壞(返回引用局部變量,未定義的行爲),第三個是破壞的,因爲它要求調用者刪除返回值,第二個幾乎可以,但需要'const'引用參數。 – juanchopanza

回答

9

您需要使用const引用,以便它們可以綁定到臨時對象:

template <class T> 
Vector<T> operator+(const Vector<T>& v1, const Vector<T>& v2) 
{ 
    Vector<T> tmp = v1; 
    tmp += v2; 
    return tmp; 
} 

如果你的類型是有效的活動,您可以使用右值引用oveloads利用的是:

template <class T> 
Vector<T> operator+(Vector<T>&& v1, Vector<T>&& v2) 
{ 
    Vector<T> tmp = std::move(v1); 
    tmp += v2; 
    return tmp; 
} 

顯然,你不應該返回一個引用或者需要被調用者刪除的東西。

+0

哦,是的,它需要在我的課堂上進行一些修改,因爲我幾乎沒有在任何地方使用'const'。謝謝 – Riko