简体   繁体   English

字符串的运算符重载

[英]Operator overloading for Strings

I cannot see whats wrong with the codesnippet below where I try to overload the operator "=". 我看不到下面的代码片段有什么问题,我试图重载运算符“ =”。 I can build it but not run it (it crashes). 我可以构建它,但不能运行它(它崩溃)。 Its due to the following syntax in the main method: 其归因于main方法中的以下语法:

string2 = "my world!";

As far as I know - on the left handside of the operator is the object that holds the operator overloaded function and recevies the string-literal (that is passed to the function as an argument) on the right side of the operator. 据我所知-运算符的左侧是持有运算符重载函数并消除运算符右侧的字符串字面量(作为参数传递给函数)的对象。

below is the full code: 下面是完整的代码:

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

you are passing a constant literal in function in this line String string("hello "); 您要在此行的函数中传递常量文字String string("hello "); and when you are doing strcpy inside String operator=(char *ch) it is trying to modify the content of a constant memory location leading the problem to crash. 当您在String operator=(char *ch)中执行strcpy时,它试图修改常量内存位置的内容,从而导致问题崩溃。

you can try by doing this 你可以这样做

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

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



return 0;
}

In the operator= you are trying to copy the contents of char* to member variable string , but it can be NULL , it may not have enough memory to hold copied string. operator=您尝试将char*的内容复制到成员变量string ,但是它可以为NULL ,它可能没有足够的内存来容纳复制的字符串。 There are also other problem in you code like not passing const reference to copy constructor etc. I think you should first learn the basics before trying to overload operators. 您的代码中还有其他问题,例如没有将const引用传递给复制构造函数等。我认为您应该在尝试重载运算符之前首先学习基础知识。

Your code is broken in many ways. 您的代码在很多方面都被破坏了。 If this is for learning purposes, you should take a look at existing implementations of std::string . 如果这是出于学习目的,则应查看std::string 现有实现 If you are planning on using that class in production code: don't , and just use std::string . 如果您打算在生产代码中使用该类, 请执行以下操作不要 ,只需使用std::string

Firstly, your String class should have value semantic, and it doesn't. 首先,您的String类应该具有值语义,而没有。 Secondly, you are not allocating any memory for your String. 其次,您没有为String分配任何内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM