C++中如何重载结构体的小于运算符(operator<)?

4
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;
    }
};

我有这个结构体,我希望为小于运算符<实现运算符重载,但是我一直得到错误“此运算符函数的参数太多”。 有人可以帮我解决这个问题吗?
2个回答

4

如果您在结构体内定义运算符,您应该执行以下操作:

bool operator<(const player& rhs) const
{
    // do your comparison
}

您需要将rhs.athis->a(以及其他每个变量)进行比较。


3

是的,你只需要一个参数:即rhs参数。因为你正在定义operator<作为成员函数(也称为方法),所以你可以通过this获得左操作数。

因此,你应该这样写:

bool operator<(const player& rhs) const
{
    //Your code using this-> to access the info for the left operand
}

如果你将运算符定义为一个独立的函数,那么你需要为两个操作数都包含参数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接