在C ++中使用深度复制进行运算符重载

时间:2018-09-27 09:04:39

标签: c++ operator-overloading

#include<iostream>
#include<cstring>
#include<conio.h>
using namespace std;
class String 
{
  char *value;
  int len;

  public:
  String()
  {
    len=0;
    value=0;
  } 
  ~String() {}

  String(char *s)
  {
    len=strlen(s);
    value=new char[len+1];
    strcpy(value,s);

  }
  String(String & s)
  {
    len=s.len;
    value=new char[len+1];
    strcpy(value,s.value);
  }


 friend String operator+(String obj1, String obj2)
  {
    String obj3;
    obj3.len=obj1.len+obj2.len;
    obj3.value=new char [obj3.len+1];

    strcpy(obj3.value,obj1.value);
    strcat(obj3.value,obj2.value);
    return obj3;
    }

   friend  String operator=(String obj1, String obj2)
    {

        String obj3;
        strcpy(obj3.value,obj1.value);
        strcat(obj3.value,obj2.value);
        return obj3;
    } 


  void display()

 { cout<<value<<endl; }

};


  int main()
 {

    String s1("Bodacious ");
    String s2("AllienBrain");
    String s3;
    s3=s1+s2;
    s3.display();

    getch(); 
 } 

因为我已经在代码中操作了运算符+,但是我也想重载operator=来使两个字符串都生效,但是当我重载+运算符时,此代码未显示任何错误,但它显示了正确的输出,即胆大的AllienBrain。

但是当我超载operator=时会抛出错误,所以有人告诉我我怎么了?

2 个答案:

答案 0 :(得分:0)

请参见how to properly overload these operators,因为operator=必须是成员函数并且必须具有单个参数,如果您想将operator+作为非成员friend函数,则对其进行声明课堂外

class String 
{
///...

  friend String operator+(String obj1, String obj2);

  String& operator=(const String& obj2)
  {
      len = obj2.len;
      value = new char[len + 1];

      strcpy(value, obj2.value);
      return *this;
  }

/// ...

};

String operator+(String obj1, String obj2)
{
    String obj3;
    obj3.len = obj1.len + obj2.len;
    obj3.value = new char[obj3.len + 1];

    strcpy(obj3.value, obj1.value);
    strcat(obj3.value, obj2.value);
    return obj3;
}

Output:

Bodacious AllienBrain

要获得有关操作符重载的更一般且强烈推荐的阅读材料,请阅读the canonical post on this site

答案 1 :(得分:0)

重载=运算符的更合适版本如下:

class String 
{
///...
String& operator=(const String& obj2)
  {
      if(this->value ){
        delete this->value;  // Free if existing
        this->value = NULL;
      }
      len = obj2.len;
      this->value = new char[len + 1];

      strcpy(this->value, obj2.value);
      return *this;
  }
///
};