c++ - 当参数声明为 const 时,为什么重载的 operator> 不起作用?

标签 c++ operator-overloading

我正在编写一个程序来模拟取招纸牌游戏。在确定技巧获胜者的函数中,我创建了一个 列表,其中包含所有花色与所领牌花色相匹配的牌。然后,我按排名降序对该列表进行排序,然后返回 list 中的第一张牌(即,与所领导的西装匹配的牌中排名最高的牌)。这是代码的相关部分:

#include <list>

enum Suits
{
    Clubs,
    Diamonds,
    Hearts,
    Spades
};

class Card
{
private:
    const Suits suit;
    const int rank;
    friend Card determineWinner(Card led, Card other1, Card other2, Card other3);
public:
    Card(Suits cardsSuit, int cardsRank) : suit(cardsSuit), rank(cardsRank) {}
    bool operator > (const Card& compareTo)
    {
        return (rank > compareTo.rank);
    }
};

Card determineWinner(Card led, Card other1, Card other2, Card other3)
{
    Suits ledSuit = led.suit;
    list<Card> eligible = { led };
    // add the cards whose suit matches the suit led to the list of cards eligible to win the trick
    if (other1.suit == ledSuit)
        eligible.push_back(other1);
    if (other2.suit == ledSuit)
        eligible.push_back(other2);
    if (other3.suit == ledSuit)
        eligible.push_back(other3);
    // sort the list of cards eligible to win the trick in descending order by rank
    eligible.sort([](const Card& card1, const Card& card2) {return (card1 > card2);});
    // the highest ranked eligible card is first in the list after the sort
    auto winner = eligible.begin();
    return *winner;
}

当我尝试运行此代码时,出现编译错误:E0349:没有运算符“>”匹配这些操作数。如果我在用作排序谓词的 lambda 函数中将 card1card2 声明为非 const,代码将按预期进行编译和执行。在 Cardoperator > 的定义中有什么我可以改变的,这将允许它用 card1card2< 编译 声明了 const,还是我应该让 well enough alone?

最佳答案

bool operator > (const Card& compareTo)
{
    return (rank > compareTo.rank);
}

这需要声明为 const 成员函数。没有 const 限定符附加到它们的签名的成员函数不能在 const 对象上调用,因为没有这个限定符,编译器不能确定没有在该函数中对该对象的状态进行了更改——如果您在签名中包含 const,编译器将强制执行此契约,如果您试图更改此函数中的对象状态,则编译将失败功能。

更正后的代码如下所示:

bool operator > (const Card& compareTo) const
{
    return (rank > compareTo.rank);
}

关于c++ - 当参数声明为 const 时,为什么重载的 operator> 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45246725/

相关文章:

c++ - 语句范围 [ c++11 ]

c++ - 在 C++ fstream 中更新文件末尾

c++ - 即使只有主函数,在主函数外部声明变量也会更改输出

c++ - 将字符传递给运算符重载的自定义流操纵器

c++ - 多个输出运算符?

c++ - 为什么要覆盖 operator()?

c++ - clang 中的 Clang : no warning with -Wdangling-gsl and curly braces initialization, 错误?

c++ - 使用 shared_ptr 和 weak_ptr 时避免间接循环引用

c++ - 为什么 operator<< 不适用于 operator- 返回的内容?

c++ - 多次使用 [x, y, z, ...]-clause 语法,不应该允许 operator[] 接受多个参数吗?