字符串运算符重载我真的不明白

string operator overloading in I really don't get it

本文关键字:明白 真的 运算符 重载 字符串      更新时间:2023-10-16

这是我的代码:

#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

右值(10)不能绑定到非const引用。您需要重写您的operator+,以int const &int作为其参数。

当你在处理它时,你想重写它,这样它也不会修改左操作数。operator +=应该修改它的左操作数,但operator +不应该。

不应该通过引用来接受int类型。只要按值取。你的问题是,你试图采取一个非const引用文字整数-改变文字的意义是什么?

也就是说,您可能会考虑不要创建这样的操作符,因为它很有可能使将来的维护人员感到困惑。