重载赋值运算符“=”

//重载赋值运算符“=”,只能重载为成员函数。
//若不写,系统提供默认赋值(按位赋值)
//注意:返回类的引用
//一般顺序:1.判断是否是同一对象
// 2.若被赋值的对象占用了动态空间,应先释放。再申请空间赋值
// 3.返回 return *this;

          String& operator= (const String& s)
          {
                if(&s == this) return *this;
                if(pChar) delete[] pChar;
                if(s.pChar == NULL) p = NULL;
                else
                {
                    pChar = new char[strlen(s.pChar)+1];
                    strcpy(pChar, s.pChar);
                }
                return *this;
            }

  

猜你喜欢

转载自www.cnblogs.com/htj10/p/10651091.html