重载 + 自己的类和 std::string 的运算符

Overload + operator for own class and std::string

本文关键字:string 运算符 std 自己的 重载      更新时间:2023-10-16

如何重载+运算符才能写出这样的东西:

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;
}