假设我有这个:
struct coor
{
int x;
int y;
COORD operator=(coor c)
{
COORD C={c.x,c.y}
return C;
}
}
我需要这样做:
coor c={0,0};
COORD C=c;
我可以将运算符重载添加到coor,但你如何做到这一点以返回左侧?
假设我有这个:
struct coor
{
int x;
int y;
COORD operator=(coor c)
{
COORD C={c.x,c.y}
return C;
}
}
我需要这样做:
coor c={0,0};
COORD C=c;
我可以将运算符重载添加到coor,但你如何做到这一点以返回左侧?
操作员=必须为对象本身的成员赋值。返回值只是为了使a = b = c类似的事情起作用。在您的情况下,这无关紧要。此外,如果有A = B,将使用=定义的 in A,如果有B = A,则使用=in B。您需要编写一个带有参数并更新其成员的=in 。COORDcoor
以下不调用 operator =:
COORD C=c;
它调用匹配的构造函数。
并且 operator= 必须返回*this这样的事情:a=b=c=d工作,但这是传统的
struct coor
{
int x;
int y;
COORD operator=(coor c)
{
COORD C;
C.x = c.x;
C.y = c.y;
return C;
}
}
要重载operator=以便将对象分配给coor对象COORD,您必须在 内部执行此操作COORD struct:
struct COORD
{
int x;
int y;
COORD& operator=(coor& c)
{
this->x = c.x;
this->y = c.y;
return *this;
}
};
但是,正如其他人所提到的,这种重载适用于以下分配:
coor c = {0,0};
COORD C;
C = c;
但不是为了
coor c = {0,0};
COORD C = c;
因为第二行实际上是调用 COORD 的构造函数,它接受一个对象coor作为参数。身体可能看起来像:
COORD(coor c):x(c.x),y(c.y)
{
}