2015-06-28 128 views
0

我想重載我的模板Vector類的+ =操作符。重載模板操作符

template<unsigned int dimensions, typename TValue> 
class Vector 
{ 
private: 
    std::array<TValue, dimensions> m_values; 
public: 
    Vector(){ 
     for (int i = 0; i < dimensions; i++){ 
      m_values[i] = TValue(); 
     } 
    }; 
    Vector(std::array<TValue, dimensions> elements){ 
     for (int i = 0; i < dimensions; i++){ 
      m_values[i] = elements[i]; 
     } 
    }; 

    inline void set(VectorDimensions dimension, TValue value){ 
     m_values[dimension] = value; 
    }; 

    inline TValue get(VectorDimensions dimension) const{ 
     return m_values[dimension]; 
    }; 

    inline unsigned int getSize() const{ 
     return dimensions; 
    }; 

    const std::array<TValue, dimensions> getValues() const{ 
     return m_values; 
    }; 

    friend ostream& operator<<(ostream& os, const Vector<dimensions, TValue>& vt) { 
     array<TValue, dimensions> values = vt.getValues(); 
     os << '['; 
     for (unsigned int i = 0; i < vt.getSize(); i++){ 
      os << values[i] << values[i+1] ? ", " : ""; 
     } 
     os << ']'; 
     return os; 
    }; 

    friend Vector<dimensions, TValue>& operator+=(const Vector<dimensions, TValue>& vt) { 
     array<TValue, dimensions> values = vt.getValues(); 
     for (unsigned int i = 0; i < vt.getSize(); i++){ 
      m_values[i] += values[i]; 
     } 
     return *this; 
    }; 

}; 

完成投入過載爲+ = opperator我得到很多下列錯誤:

錯誤C2805:二進制 '操作符+ =' 太少參數

錯誤C4430:缺少類型說明符 - 假定爲int。注意:C++不支持default-int

錯誤C2334:在'{'之前的意外標記(s)跳過明顯的功能體。

錯誤C2238:在';'之前的意外標記(s)

語法錯誤:缺少';' '<'

錯誤C2143:語法錯誤:缺少';' '++'之前

錯誤C2143:語法錯誤:在'之前'缺少''''''

錯誤C2059:語法錯誤: '迴歸'

錯誤C2059:語法錯誤: '對'

錯誤C2059:語法錯誤: ')'

的,爲什麼解釋或者這些錯誤如何實際上由我做錯的事情引起的可能是有用的。謝謝

+0

那麼,主要的錯誤是,'+ ='實際上分別作爲運算符'+'和'='。 'a + = b'與'a = a + b'相同,所以你應該實現'operator +',如果需要'operator ='。 –

+2

'operator + ='必須作爲一個參數的成員函數實現,或者一個非成員採用兩個參數。您試圖將其作爲一個非成員來執行一個參數:因此「參數太少」錯誤。把'朋友'放在前面。 –

+1

@ZachP:恰恰相反,我會說(如果我正確理解你的話)。 'operator +'應該用'operator + ='來實現。 –

回答

0

我能夠通過從+ =運算符定義之前刪除friend關鍵字來阻止錯誤。根據這一頁http://en.cppreference.com/w/cpp/language/operators

class X { 
public: 
    X& operator+=(const X& rhs) // compound assignment (does not need to be a member, 
    {       // but often is, to modify the private members) 
    /* addition of rhs to *this takes place here */ 
    return *this; // return the result by reference 
    } 

    // friends defined inside class body are inline and are hidden from non-ADL lookup 
    friend X operator+(X lhs,  // passing first arg by value helps optimize chained a+b+c 
        const X& rhs) // alternatively, both parameters may be const references. 
    { 
    return lhs += rhs; // reuse compound assignment and return the result by value 
    } 
}; 

這是+和+ = opperators應該如何超載。

+0

'operator <<'必須作爲非成員函數來實現; 「朋友」就是如此。 'operator + ='可以作爲非成員來實現 - 但是它應該有兩個參數。你的只有一個,這隻有在它是一個成員函數時纔有效。滴下'朋友'就是這麼做的。 –

+0

謝謝,現在聽起來很愚蠢,但我還沒有發佈函數不能成爲朋友和班級成員的真正意義。 –

+0

那麼,你可以讓一個類的成員函數成爲另一個類的一個朋友。但這不是你的代碼所做的。 –