c++ - 重载运算符 +。字符串类

标签 c++ operator-overloading overloading

我自己写字符串类。我重载了 + 运算符。它工作正常,但后来我试图等同于 cstr = str +pop ,它什么也没做。 `你可以在 main() 函数中看到我的错误。编译器没有给出任何错误。

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

class S {

public:
          S();
          S(const char *str);
          S(const S &s);

         ~S() { delete []string;}
          S  &operator  =(const S   &s);

          int  lenght() const {return l     ;}
      char*  strS() const {return string;}

      friend ostream &operator <<(ostream &, const S &first) {cout<<first.string;}
      friend S    operator+ (const S& first, const S& second);

private:
          char *string;
          int l;

};

int main(){
S pop("Q6");
S str("M5");

S cstr = str +pop; // works correct
cout<<str;

str = str + pop;
cout<<str ;        // doesnt work, it doesnt write in terminal

return 0;
}
S::S()
{
    l = 0;
    string = new char[1];
    string[0]='\0';
}

S::S(const char *str)
{
    l      = strlen(str);
    string = new   char[l+1];
    memcpy(string, str, l+1);
}

S::S(const S &s)
{
     l = s.l;
     string = new char[l+1];
     memcpy(string,s.string,l+1);
}

S &S::operator=(const S &s)
{
    if (this != &s)
    {
        delete []string;
        string = new char[s.l+1];
        memcpy(string,s.string,s.l+1);
        return *this;
    }
    return *this;
}

S    operator +(const S& first, const S& second)

{
    S temp;
    temp.string = strcat(first.strS(),second.strS());
    temp.l      = first.lenght() + second.lenght();

  return temp;
 }

我期待着您的帮助。

最佳答案

您的运算符(operator)有错误!

S temp;
//^^^^ has only one byte buffer!!!
temp.string = strcat(first.strS(),second.strS());
//   1 byte   ^^^^^ strcat appends second.strS to first.strS

你应该为 temp 重新分配内存:

S temp;
temp.l      = first.lenght() + second.lenght();
delete [] temp.string; // !!!! - 
temp.string = new char[temp.l + 1]; // !!!!
// you should have another c-tor which can allocate memory!!!
// like: S(unsigned length, unsigned char c = '\0') 
strcpy(temp.string, first.strS());
strcat(temp.string, second.strS());

除了这个明显的错误 - 你还应该注意异常 - 例如 std::bad_alloc。查看 copy-and-swap 习惯用法以获得更好的方法来完成此任务。

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

相关文章:

c++ - 防病毒软件将已编译的C++文件检测为木马

c++ - 重载 operator= 在类之间交换数据

c++ - 矩阵类和 operator= 重载

c++ - 机器码层虚函数和条件执行的区别

c++ - 如何在 STL map 上使用 binary_search

C++ boost tcp 服务器

python - python中的运算符重载,对象位于运算符的右侧

c++ - 动态转换还是函数重载?

c++ - 为什么我的日志在 std 命名空间中?

java - 它是否重载或覆盖?