c++ - 字符串的运算符重载

标签 c++ string operator-overloading

我看不出下面的代码片段有什么问题,我尝试重载运算符“=”。 我可以构建它但不能运行它(它崩溃了)。这是由于 main 方法中的以下语法造成的:

string2 = "my world!";
据我所知 - 运算符的左侧是保存运算符重载函数的对象,并接收运算符右侧的字符串文字(作为参数传递给函数)。

下面是完整代码:

#include <iostream>
using namespace std;

class String {

public:
char *string;
String(char *ch) {
    string = ch;
}
String (String &string_obj) {
    string = string_obj.string;
}
String operator=(char *ch) {

    strcpy(string, ch);

    return *this;
}

};

ostream &operator<<(ostream &stream, String obj) {

    stream << obj.string;

    return stream;
}



int main() {

   String string("hello ");
   String string2(string);
   cout << string << string2;

   string2 = "my world!";
   cout << string2;



return 0;
}

最佳答案

您在这一行中的函数中传递了一个常量文字String string("hello "); 当您在 String operator=(char *ch) 中执行 strcpy 时,它会尝试修改常量内存位置的内容,从而导致问题崩溃。

你可以尝试这样做

int main() {
   char str[]="hello";    
   String string(str);
   String string2(string);
   cout << string << string2;

   string2 = "my world!";
   cout << string2;



return 0;
}

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

相关文章:

C++ << 相同类型的运算符重载

C - 如何扫描仅在符号后输入的 int

python - 从文本文件中的行创建字符串列表的大多数 pythonic 方法?

vb.net - 在VB中的字符串中使用左双引号

C++运算符编译错误

python - 是否可以在 Python 中重载对 vars(object) 的调用?

c++ - 如果我将 basic_stream<char> 与 codecvt_utf16<char> facet 的语言环境相结合,会发生什么情况?

c++ - VS 2010 无法打开源文件 "string"

c++ - 如何在搜索表单的 QMessageBox 中包含 QLineEdit

c++ - 函数原型(prototype)