为什么重载运算符>在参数声明 const 时不起作用?

Why won't overloaded operator> work when the arguments are declared const?

本文关键字:const 声明 不起作用 参数 运算符 重载 gt 为什么      更新时间:2023-10-16

我正在编写一个程序,模拟一个花招纸牌游戏。在确定技巧获胜者的函数中,我创建了花色与牌头的花色匹配的所有牌的list。然后,我按等级降序对该列表进行排序,然后返回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: no operator ">" matches these operands。如果我在用作排序谓词的 lambda 函数中将card1card2声明为非const,则代码将按预期编译和执行。我可以在Cardoperator >的定义中更改一些东西,以允许它与card1一起编译并card2声明const,还是我应该独自离开?

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

这需要声明为 const 成员函数。无法在const对象上调用未附加const限定符的成员函数,因为如果没有此限定符,编译器将无法确定该函数中的对象状态没有发生任何更改 - 如果您在签名中包含const,编译器将强制执行此协定, 如果尝试更改此函数中对象的状态,则无法编译。

更正后的代码如下所示:

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