C++之赋值操作符

来源:互联网 发布:c语言null包含头文件 编辑:程序博客网 时间:2024/05/16 14:23
//修改上例,采用赋值操作符的方式初始化对象
  #include<iostream.h>
  #include<string.h>
  class string
  {
  private:
   char * str;
  public:
  
  string(char * s=" ")
  {
   cout << "在构造函数中/n";
   int size=strlen(s);
   str=new char[size+1];
   strcpy(str,s);
  }
  string& operator=(string & ss)//赋值操作符方式
  {
   cout << "赋值操作符/n";
   delete str;
   str=new char[strlen(ss.str)+1];
   strcpy(str,ss.str);
   return *this;
  }
  ~string()
  {delete str;}
  void showstring()
  {cout << str << endl;}
  };
  void main()
  {
   string s1="内存中得字符串";
   cout << "s1 = ";
   s1.showstring();
   string s2;
   s2=s1;
   cout << "s2 = ";
   s2.showstring();
  }  
原创粉丝点击