为什么重载运算符需要返回=对象?

Nir*_*van 2 c++ return operator-overloading inner-classes assignment-operator

class sample
{
  private:
    int radius;
    float x,y;
  public:
    circle()
     {

     }
    circle(int rr;float xx;float yy)
     {
      radius=rr;
      x=xx;
      y=yy;
     }

 circle operator =(circle& c)
     {
      cout << endl<<"Assignment operator invoked";
      radius=c.radius;
      x=c.x;
      y=c.y;
      return circle(radius,x,y);
     }


}

int main()
{
 circle c1(10,2.5,2.5);
 circle c1,c4;
 c4=c2=c1;
}
Run Code Online (Sandbox Code Playgroud)

在重载'='函数中的语句

radius=c.radius;
x=c.x;
y=c.y;
Run Code Online (Sandbox Code Playgroud)

本身使所有c2的数据成员都等于c1,那么为什么需要返回?类似地,在c1 = c2 + c3中,使用重载+运算符添加c2和c3,并将值返回到c1,但不会变为c1 =,因此我们不应该使用another =运算符来分配总和c2和c3到c1?我糊涂了.

ild*_*arn 6

它不是必需的(即void返回类型是合法的),但标准做法是返回一个引用,*this以允许分配链接而不会产生任何效率开销.例如:

class circle
{
    int radius;
    float x, y;

public:
    circle()
      : radius(), x(), y()
    { }

    circle(int rr, float xx, float yy)
      : radius(rr), x(xx), y(yy)
    { }

    circle& operator =(circle const& c)
    {
        std::cout << "Copy-assignment operator invoked\n";
        radius = c.radius;
        x = c.x;
        y = c.y;
        return *this;
    }
};

int main()
{
    circle c1(10, 2.5f, 2.5f);
    circle c2, c3;
    c3 = c2 = c1;
}
Run Code Online (Sandbox Code Playgroud)

正如你所做的那样,按返回一个新对象肯定是非标准的,因为它创造了不必要的临时性.