运算符=重载

2 c++ operator-overloading assignment-operator

假设我有这个:

struct coor
{
   int x;
   int y;
   COORD operator=(coor c)
   {
      COORD C={c.x,c.y}
      return C;
   }
}
Run Code Online (Sandbox Code Playgroud)

我需要这样做:

coor c={0,0};
COORD C=c;
Run Code Online (Sandbox Code Playgroud)

我可以添加运算符重载coor,但是你怎么做到返回左侧?

Nul*_*teя 5

运算符=必须为对象本身的成员赋值.返回值只是为了制作a = b = c和类似的东西工作.在你的情况下,这是无关紧要的.此外,如果你有A = B,将使用=定义的in A,如果你有B = A,则使用=in B.你需要的是写=COORD那取coor的这个参数和更新成员.

以下不调用运算符=:

COORD C=c;
Run Code Online (Sandbox Code Playgroud)

它调用匹配的构造函数.

并且运营商=必须返回这样*this的事情:a=b=c=d工作但这是传统的