字符串运算符重载我真的不明白
string operator overloading in I really don't get it
这是我的代码:
#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引用文字整数-改变文字的意义是什么?
也就是说,您可能会考虑不要创建这样的操作符,因为它很有可能使将来的维护人员感到困惑。
相关文章:
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- 我不明白这段代码是如何对这个pythonlist()进行排序的,也不明白如何用C++中的向量来重现它
- 不明白迭代器,引用和指针失效,一个例子
- 字节真的是最小可寻址单元吗
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 如何在 std::vector 中找到<bool>哪些索引是真的?
- std::string 的对象真的可以移动吗?
- 在这种情况下,我真的复制了字节还是复制了字符?
- 而循环:简单的除法程序输出零,不明白为什么
- int8_t和uint8_t真的是整数吗?它们有什么用?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 我不明白为什么我的代码不起作用并且需要更长的时间来运行
- 查找不等式为真的次数时出现问题
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 你如何理解"std: :forward is just syntactic sugar"?这是真的吗?
- "std::forward"和"std::move"真的不生成代码吗?
- 字符串运算符重载我真的不明白