C++:字符串运算符重载

标签 c++ operator-overloading c++-standard-library

我可以重载现有类中的现有函数/运算符吗?

我想做的是:

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

string& string::operator<<(const string& str) {
  this->append(str);
}

但这给了我错误:

test.cpp:5: error: too few template-parameter-lists

我该怎么做?或者我不能?

最佳答案

除非您修改该类的定义,否则您不能向该类添加成员函数。请改用免费功能:

string& operator<<(string & lhs, const string & rhs) {
    return lhs += rhs;
}

关于C++:字符串运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11515925/

相关文章:

c++ - 为什么 std::accumulate 在 C++20 中没有被设为 constexpr?

c++ - 插入到 std::unordered_multimap 时有没有办法避免散列/equalityChecking?

c++ - 如何使用反向迭代器从 `std::set` 删除元素?

c++ - 存储在父类中的派生类数组

c++ - 如何使用 std::valarray 来存储/操作连续的二维数组?

delphi - 重载三个扩展记录的添加运算符

python - 卡住函数参数

c++ - 忽略 iOS 应用程序中的库以针对模拟器进行编译

c++ - 不适合内存的随机访问容器?

c++ - 使用模板C++重载运算符