0

これは私のコードです:

#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

4

2 に答える 2

14

右辺値 ( 10) は非 const 参照にバインドできません。パラメータとして anまたは an だけoperator+を取るように your を書き換える必要があります。int const &int

あなたがそれをしている間、あなたはそれを書き直したいので、左オペランドも変更しません。operator +=は左オペランドを変更する必要がありますが、変更しoperator +ないでください。

于 2013-01-14T20:00:49.283 に答える
3

参照によって int を取得しないでください。値でそれを取るだけです。あなたの問題は、リテラル整数への非定数参照を取得しようとしていることです-リテラルを変更する意味は何ですか?

そうは言っても、将来のメンテナーを混乱させる可能性がかなりあるため、そのようなオペレーターを作成しないことを検討するかもしれません.

于 2013-01-14T20:01:15.710 に答える