c++,operator=

operator=为什么值得注意?

从语法上讲,下面的程序可以编译通过,我在另一篇笔记示例里面也这样用了。

class A1
{
public:
    int operator=(int a)//参数是int,语法通过但逻辑不通。
    {
        return 8;
    }

    int operator+(int a)
    {
        return 9;
    }

    int operator=(A1 &a)//返回int,既无意义也不合逻辑,
    {
        cout<<"operator=(A1 &a)"<<endl;
        return 0;
    }
};  
// http://www.cnblogs.com/mylinux/p/4094808.html

实际上如图拷贝构造函数一样,我们要考虑更多问题:

1.浅拷贝的问题。[1]//构造函数,operator=与构造函数的道理相同。

注意事项:[2]  //Effective_C++

2.为什么opreator=要返回*this?
  为了支持a=b=c这样的连锁调用
3.为什么不返回const GoodObject&?
  为了和编译器(a=b)=c这样的操作兼容
4.为什么要传入const GoodObject& rhs
  主要支持以下操作:
  GoodObject a;
  const GoodObject b;
  a = b;
5.为什么要有if (this != &rhs)这样的判断
  主要是避免自我赋值a=a这样的情况发生.
6.不要忘记重写拷贝构造函数

7.示例:[3]

参考网友的示例:

class SampleClass
{
private:
         int a;
         double b;
         float* p;
public:
         SampleClass& operator= (const SampleClass& s)
         {
                   if(this == &s) return *this; // 解决自我赋值的一句话
                   a = s.a;
                   b = s.b;
                   delete p;
                   p = new float(*s.p);
                   return *this;
         }
};

 书上是这样写的://虽然多了个tmp,但建议参考

SampleClass& operator= (const SampleClass& s)
{
         if(this == &s) return *this; //
         a = s.a;
         b = s.b;
         float* tmp = p; // 先保存了旧的指针
         p = new float(*s.p); // 再申请新的空间,如果申请失败,p仍然指向原有的地址空间
         delete tmp; // 能走到这里,说明申请空间是成功的,这时可以删掉旧的内容了
         return *this;
}

参考:

1.C++深浅拷贝浅析
  http://www.jizhuomi.com/software/291.html

2.operator=函数.

  http://blog.csdn.net/howlet2/article/details/5090756

3.读书笔记_Effective_C++_条款十一:在operator=中处理自我赋值
  http://www.cnblogs.com/jerry19880126/archive/2013/03/21/2972648.html

原文地址:https://www.cnblogs.com/mylinux/p/4113266.html