2011-02-09 57 views
1

我對朋友操作符重載感到困惑。如果我在頭文件中編寫friend運算符重載函數,它沒有問題,但是一旦將函數移動到類文件,它會給我以下錯誤。我搜索了一些樣本,他們都在頭文件中寫了函數。我做錯了什麼?謝謝。C++的朋友操作符+超載

...: error: expected ‘,’ or ‘...’ before ‘&’ token 
...: error: ISO C++ forbids declaration of ‘statisticain’ with no type 
...: error: ‘main_savitch_2C::statistician operator+(int)’ must have an argument of class or enumerated type 


// a.h 
class A 
{ 
    public: 
     friend A operator + (const A &a1, const A &a2); 
}; 

// a.cpp 
#include "a.h" 
A operator + (const A &a1, const A &a2) 
{ 
    // 
} 
+0

該代碼適用於我。你的**實際**代碼是什麼樣的? – 2011-02-09 06:19:04

+1

因爲每個人都給出了關於如何正確地重載operator +的建議,[這裏是](http://codepad.org/8E9m5A7a)我的建議。 – 2011-02-09 06:58:12

回答

3

從你得到錯誤信息:

ISO C++ forbids declaration of ‘statisticain’ with no type 

我認爲你拼錯「統計學家」通過逆轉的最後兩個字母(請注意,你有「statisticain」而不是「統計員。 「)

這應該與頭文件或.cpp文件中是否實現了operator+無關。

+0

哦,是的,我沒有仔細閱讀錯誤信息。非常感謝。 – Kyeteko 2011-02-09 07:18:20

1

我同意上一個答案。另外,如果我可能會問,爲什麼當這個函數和friend這兩個參數和返回類型是同一個類時呢?爲什麼不把它作爲一個成員,所以第一個參數是由this運算符隱式傳遞的?

+5

@ darkphoenix-(這可能屬於評論而不是答案,順便說一句)。你可以使`operator +`函數成爲一個自由函數而不是一個成員函數,這樣如果存在從其他類型到`A`的隱式轉換,則可以考慮運算符。如果它是一個成員,那麼如果第一個操作數不是`A`,則不會找到該函數。如果需要訪問類數據成員,它將成爲「朋友」。 – templatetypedef 2011-02-09 06:27:04

0

將兩個參數版本移出類聲明。或者只使用一個參數和這個指針。

下面是一個簡短的現實世界的例子。

//complexnumber.h 
    class ComplexNumber 
    { 
     float _r; 
     float _i; 

     friend ComplexNumber operator+(const ComplexNumber&, const ComplexNumber&); 

     public: 
      ComplexNumber(float real, float img):_r(real),_i(img) {} 
      ComplexNumber& operator + (const ComplexNumber &other); 
    }; 

    ComplexNumber operator+(const ComplexNumber &c1, const ComplexNumber& c2); 


//complexnumber.h 
    ComplexNumber operator+(const ComplexNumber &c1, const ComplexNumber& c2) 
    { 
     return ComplexNumber(c1._r+c2._r, c1._i+c2._i); 
    } 


    // static 
    ComplexNumber& ComplexNumber::operator + (const ComplexNumber &other) 
    { 
     this->_r = this->_r + other._r; 
     this->_i = this->_i + other._i; 

     return *this; 

    }