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

时间:2012-04-11 16:03:45

标签: c++ operator-overloading return 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;
}

在过载的&#39; =&#39;函数语句

radius=c.radius;
x=c.x;
y=c.y;

本身使所有c2的数据成员都等于c1&s,那么为什么需要返回? 类似地,在c1 = c2 + c3中,使用重载+运算符添加c2和c3,并将值返回到c1,但不会变为c1 =,因此我们不应该使用另一个=运算符将c2和c3的总和分配给c1?我很困惑。

4 个答案:

答案 0 :(得分:6)

不是需要(即void返回类型是合法的),但标准做法是返回对*this的引用,以允许分配链接而不进行任何操作效率开销。 E.g:

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;
}

正如你所做的那样,通过 value 返回一个新对象肯定是非标准的,因为它会产生不必要的临时值。

答案 1 :(得分:3)

这不是强制性的,但是返回对*this的引用可以让人们链接分配,就像基本类型一样。

但是,只有当赋值运算符按值或const引用获取其参数时,这才有效;你的非const引用,这是你应该只在特殊情况下做的事情。

circle & operator=(circle const & c) {
    radius = c.radius;
    x = c.x;
    y = c.y;
    return *this;
}

对于这样的运算符,c4=c2=c1将进行编译,并且会将c1分配给c2,然后将c2的新值分配给{{ 1}}。

答案 2 :(得分:2)

支持a = b = c的成语。

你也做错了;返回值应为circle &而不是circle,返回值应为return *this;

答案 3 :(得分:0)

您可以从赋值运算符函数返回* this,以返回对当前对象的引用。您还可以创建

的值
circle& operator = (circle& c)
{
// do assignments
    return *this;
}
相关问题