2013-01-14 32 views
0

這是我的代碼:串C++操作符重載 - 我真的不明白這一點

#include <iostream> 
#include <string.h> 
using namespace std; 

string& operator+(string & lhs, int & rhs) { 
    char temp[255]; 
    itoa(rhs,temp,10); 
    return lhs += temp; 
} 

int main() { 
    string text = "test "; 
    string result = text + 10; 
} 

結果是:

test.cpp: In function 'int main()': 
test.cpp:15:26: error: no match for 'operator+' in 'text + 10' 
test.cpp:15:26: note: candidates are: 
/.../ 

而且應該是test 10

回答

14

右值(10)無法綁定到非const引用。您需要重寫您的operator+,以採用int const &或僅將int作爲其參數。

當你在它的時候,你想重寫它,所以它不會修改左操作數。一個operator +=應該修改它的左操作數,但operator +不應該。

3

你不應該參考int。只要看看它的價值。你的問題是你試圖對文字整數取非const引用 - 改變文字的意義是什麼?

這就是說,你可能會考慮不要創建這樣一個運營商,因爲它有一個公平的機會混淆未來的維護者。