对象赋值的语义

若未声明或实现该赋值操作符,编译器将自动生成一个默认赋值操作符。

实现类似以下代码:

1 TPoint2D::operation = (const TPoint2D& source)
2 {
3     this->xcoordinate = source.xcoordinate;
4     this->ycoordinate = source.ycoordinate;
5     return *this;
6 }

实现: 1 TPoint2D::operation = (const TPoint2D& source 2 {

 3     if (this == &source)//自我赋值检查
 4         return *this;
 5     this->ssn = source.ssn;
 6     //接下来,需要赋值name中的字符
 7     //如果name中空间充足,则只需复制字符即可
 8     //否则,删除name所指向的现有内存,然后分配新的内存块
 9     //最后,复制字符.
10     if (source.name != 0)
11     {
12         int nameLength = strlen(source.name);
13         int thisNameLength = (this->name) ? strlen(this->name) : 0;
14         if (nameLength <= thisNameLength)
15             strcpy(this->name, source.name);
16         else
17         {
18             delete[]this->name;
19             name = new char[nameLength + 1];
20             strcpy(this->name, source.name);
21         }
22     }
23     else
24     {
25         delete[]this->name; this->name = 0;
26     }
27     //address重复上面的步骤完成
  return *this; 28 }
原文地址:https://www.cnblogs.com/zhengzhe/p/6528359.html