assignment operator overloading in c++

前端 未结 6 1994
醉梦人生
醉梦人生 2021-02-01 15:07

I have used the following code for assignment operator overloading:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs         


        
6条回答
  •  误落风尘
    2021-02-01 15:33

    Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

    SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
    {
        itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
        return *this;
    }
    

    I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

    As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

提交回复
热议问题