【问题标题】:Why is a return needed in the overloaded operator = for objects?为什么对象的重载运算符 = 需要返回?
【发布时间】:2012-04-23 23:29:15
【问题描述】:
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;
}

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

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

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

【问题讨论】:

标签: c++ operator-overloading return inner-classes assignment-operator


【解决方案1】:

这不是需要(即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;
}

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

【讨论】:

    【解决方案2】:

    是为了支持a = b = c的成语。

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

    【讨论】:

      【解决方案3】:

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

      circle& operator = (circle& c)
      {
      // do assignments
          return *this;
      }
      

      【讨论】:

        【解决方案4】:

        这不是强制性的,但返回对 *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 的新值分配给c4

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-22
          • 1970-01-01
          • 2015-05-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多