我正在编写一个程序来模拟取招纸牌游戏。在确定技巧获胜者的函数中,我创建了一个 列表
,其中包含所有花色与所领牌花色相匹配的牌。然后,我按排名降序对该列表进行排序,然后返回 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 函数中将 card1
和 card2
声明为非 const
,代码将按预期进行编译和执行。在 Card
的 operator >
的定义中有什么我可以改变的,这将允许它用 card1
和 card2< 编译
声明了 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/