【问题标题】:Operator overloading using deep copy in c++在 C++ 中使用深拷贝的运算符重载
【发布时间】:2018-09-27 09:04:38
【问题描述】:
#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= 以连接两个字符串,但是当我重载 + 运算符时此代码没有显示错误,但它显示了正确的输出,即 Bodacious AllienBrain .

但是当我超载 operator= 时,它会抛出错误,所以有人告诉我我有什么问题吗?

【问题讨论】:

标签: c++ operator-overloading


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2010-11-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多