我發現了很多有關此錯誤的討論,但是我沒有嘗試過迄今爲止所做過的工作。我試圖重載「+」運算符,它只適用於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個加數工作呢?
第一個版本總是被破壞(返回引用局部變量,未定義的行爲),第三個是破壞的,因爲它要求調用者刪除返回值,第二個幾乎可以,但需要'const'引用參數。 – juanchopanza