c ++运算符<重载结构

时间:2015-04-10 13:32:11

标签: c++ operator-overloading

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

我有这个结构,我希望为运算符&lt;提供运算符重载,但我不断收到错误“此运算符函数的参数太多”。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

如果在结构中定义运算符,则可以执行

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

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

答案 1 :(得分:1)

是的,您应该只有一个参数:rhs参数。由于您将operator<定义为成员函数(也称为方法),因此您可以通过this免费获得左操作数。

所以你应该这样写:

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

如果您已将操作符定义为独立函数,则需要包含两个操作数的参数。