重载 + 自己的类和 std::string 的运算符
Overload + operator for own class and std::string
如何重载+运算符才能写出这样的东西:
MyString str("He is");
str = str + " a cat";
我的字符串:
class MyString {
public:
MyString();
MyString(const char *text);
MyString(const MyString &stringToCopy);
~MyString();
MyString& operator=(const MyString &otherString); // It works
MyString& operator=(const char *text); // It works
MyString& operator+=(const MyString &otherString); // It works
MyString& operator+=(const char *text); // It works
private:
char *_chars;
int _length;
};
我目前的想法(但它不起作用(:
MyString operator+(MyString &firstString, std::string &text) {
std::cout << "text: " << text << std::endl; // It not prints
...
}
我没有错误,但运算符方法没有调用。
cout << str.toStandard(); // Prints " cat". Without first char
编辑:
我将每个 std::string 参数更改为常量字符*
MyString MyString::operator+(const char *text) {
MyString newString(*this);
newString.pushText(text);
cout << "test: " << newString.toStandard() << endl; // Prints correct append
return newString;
}
在 main(( 中:
cout << (str + "teest").toStandard() << endl; // Not prints
在控制台中,我收到错误代码:-1073741819
您可以按如下方式声明operator+
:MyString MyString::operator+ (const MyString& strToAdd) const;
或MyString MyString::operator+ (const std::string strToAdd) const;
这类似于+=
运算符,但您创建一个新MyString
并将其返回,而不是将其追加到MyString
对象。
在我个人看来,operator+
最好是MyString
的成员,但这也有效:
MyString operator+ (const MyString& addStr, const std::string addStr2)
{
MyString str(addStr);
str += MyString(addStr2);
return str;
}
相关文章:
- 重载 + 自己的类和 std::string 的运算符
- 运算符'<'不能应用于类型 'string' 和 'string' 的操作数
- std::string == 运算符在代码中不起作用
- 使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
- ostream 运算符<< 为获取 STL 容器而过载,传递 std::string 会破坏它?
- 错误:为"运算符 std::string {aka std::__cxx11::basic_string}"指定的返回类型<char>
- 用std::string覆盖[]运算符
- 为std::string重载运算符+是个坏主意吗
- 为什么重载运算符不与 std::string 一起使用 msvc /MD 标志
- std::string [] 运算符和 at() 之间的区别
- msvc /permissive- std::string 重载运算符 '=' 不明确
- 错误:C2679 二进制"==":未找到采用类型 'const std::string' 的右侧操作数的运算符(或者没有可接受的转换)
- 重载一对 <std::string, std::Set 的<<运算符>
- 二元运算符"<<"不能应用于类型 "wostream" 和 "string" 的表达式
- 为什么在std :: string上尺寸运算符会产生意外结果
- std::string 的转换运算符无法处理赋值
- 仍然得到二进制"<<":没有找到需要右手的<string>运算符
- g++ L "string~" + 运算符,如 Visual C++
- std::string运算符[]如何返回引用而不是字符
- std::string运算符+与stringstream的性能