C++ operator< 重载结构
c++ operator< overloading struct
struct player
{
string name;
int a;
int v;
int s;
bool operator< (const player lhs, const player rhs)
{
if ((lhs.a < rhs.a)
|| ((lhs.a == rhs.a) && (lhs.v < rhs.v))
|| ((lhs.a == rhs.a) && (lhs.v == rhs.v) && (lhs.s > rhs.s))
|| ((lhs.a == rhs.a) && (lhs.v == rhs.v) && (lhs.s == rhs.s) && (lhs.name < rhs.name))
)
return true;
else
return false;
}
};
我有这个结构,我希望为运算符 < 重载运算符,但我一直收到错误 "too many parameters for this operator function"。有人可以帮我吗?
如果您在结构中定义运算符,您会这样做
bool operator<(const player& rhs) const
{
// do your comparison
}
您可以将 rhs.a
与 this->a
(以及每个其他变量)进行比较
是的,您应该只有一个参数:rhs
参数。由于您将 operator<
定义为成员函数(又名方法),因此您可以通过 this
.
免费获得左操作数
所以你应该这样写:
bool operator<(const player& rhs) const
{
//Your code using this-> to access the info for the left operand
}
如果您将运算符定义为独立函数,那么您将需要为两个操作数都包含参数。
struct player
{
string name;
int a;
int v;
int s;
bool operator< (const player lhs, const player rhs)
{
if ((lhs.a < rhs.a)
|| ((lhs.a == rhs.a) && (lhs.v < rhs.v))
|| ((lhs.a == rhs.a) && (lhs.v == rhs.v) && (lhs.s > rhs.s))
|| ((lhs.a == rhs.a) && (lhs.v == rhs.v) && (lhs.s == rhs.s) && (lhs.name < rhs.name))
)
return true;
else
return false;
}
};
我有这个结构,我希望为运算符 < 重载运算符,但我一直收到错误 "too many parameters for this operator function"。有人可以帮我吗?
如果您在结构中定义运算符,您会这样做
bool operator<(const player& rhs) const
{
// do your comparison
}
您可以将 rhs.a
与 this->a
(以及每个其他变量)进行比较
是的,您应该只有一个参数:rhs
参数。由于您将 operator<
定义为成员函数(又名方法),因此您可以通过 this
.
所以你应该这样写:
bool operator<(const player& rhs) const
{
//Your code using this-> to access the info for the left operand
}
如果您将运算符定义为独立函数,那么您将需要为两个操作数都包含参数。