我試圖通過編寫一些簡單,愚蠢的測試來理解操作符重載的概念。我認爲這可能是有用的,因爲這有助於我更好地理解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;
}
該運算符應該被稱爲'+ ='或'<<'! '+'操作符不應該修改對象。 – leemes