【问题标题】:Operator = overloading运算符 = 重载
【发布时间】:2012-09-14 14:59:29
【问题描述】:
假设我有这个:
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 中添加运算符重载,但要如何返回左侧呢?
【问题讨论】:
标签:
c++
operator-overloading
assignment-operator
【解决方案1】:
要重载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)
{
}
【解决方案2】:
操作员= 必须为对象本身的成员赋值。返回值只是为了使a = b = c 和类似的东西起作用。在您的情况下,这无关紧要。此外,如果您有A = B,则将使用A 中定义的=,如果您有B = A,则使用B 中的=。
您需要在COORD 中编写一个=,它采用coor 参数并更新其成员。
并且以下不调用operator=:
COORD C=c;
它调用一个匹配的构造函数。
对于这样的事情,operator= 必须返回 *this:a=b=c=d 才能工作,但这是常规的
【解决方案3】:
struct coor
{
int x;
int y;
COORD operator=(coor c)
{
COORD C;
C.x = c.x;
C.y = c.y;
return C;
}
}