c++ - 为什么在对象的重载运算符 = 中需要返回?

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

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

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

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

最佳答案

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

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

关于c++ - 为什么在对象的重载运算符 = 中需要返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10109676/

相关文章:

c++ - 重载 operator<< 用于 ostream

Python 语法错误 : ("' return' with argument inside generator", )

php函数返回0?

c++ - 运算符重载 : Simple Addition. .. 错误 C2677:二进制 '+':未找到具有类型 ___ 的全局运算符(或没有可接受的转换)

scala - 我应该在多行 Scala 方法中使用返回吗?

c++ - 在 OpenCV 中展开一组矩形以形成正方形网格

c++ - 高级函数指针?

c++ - 在一个函数容器中存储和调用不同参数的函数

c++ - for 语句中的 constexpr

c++ - C++ 中的运算符重载