2013-02-02 76 views
2

我試圖通過編寫一些簡單,愚蠢的測試來理解操作符重載的概念。我認爲這可能是有用的,因爲這有助於我更好地理解C++。重載'+'操作符不編譯

爲什麼這個例子實現了一個級聯運算符Animal class和std::string不能編譯? G ++給了我以下錯誤:

extra qualification 'Animal::' on member 'operator+' [-fpermissive]

這是代碼:

#include <iostream> 
using namespace std; 

class Animal { 

public: 
    string _type; 
    string _name; 
    string _sound; 


    Animal & Animal::operator+(const string & o); 
}; 


Animal & Animal::operator+(const string & o) { 
    cout << "plus operator \n"; 
    this->_name=o; 
    return *this; 
} 


int main(int argc, char ** argv) { 
    Animal a; 

    a+"hhh"; 
    cout<<a._name; 
    return 0; 
} 
+3

該運算符應該被稱爲'+ ='或'<<'! '+'操作符不應該修改對象。 – leemes

回答

4
Animal & Animal::operator+(const string & o); 

無效。它應該是:

Animal & operator+(const string & o); 

而且,你的一個簡單的加法運算的執行,導致一個操作數的修改。這是從來沒有加法運算符的好處。

例如:

int a, b = 5, c = 3; 
a = b + c; 

這並不改變任何操作數的值;它不會改變bc,並返回完全不同的實例。

因此,您不應重載加法運算,但加法賦值複合運算符(+=):

Animal & operator+=(const string & o); 

當然和變革的實施,並相應地調用它:

Animal & Animal::operator+=(const string & o) { 
    cout << "plus operator \n"; 
    this->_name=o; 
    return *this; 
} 

而且:

a += "hhh"; 
0

不需要原型中的,因爲它已經在Animal類中。只需使用:

Animal & operator+(const string & o); 
2

operator+內部類並不需要合格的,恰恰是因爲,它是在類中聲明聲明:

class Animal { 
    // ... 
    Animal& operator+(const string& o); 
} 

這一規定是必要的,當你定義這個函數是因爲你在類的外面定義它 - 編譯器需要知道函數屬於哪個類。

0

Animal::資格應的成員函數的定義可以使用,而不是在聲明。因此,將您的運營商聲明更改爲:

Animal & operator+(const string & o);