为什么重载运算符>在参数声明 const 时不起作用?
Why won't overloaded operator> work when the arguments are declared const?
我正在编写一个程序,模拟一个花招纸牌游戏。在确定技巧获胜者的函数中,我创建了花色与牌头的花色匹配的所有牌的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 函数中将card1
和card2
声明为非const
,则代码将按预期编译和执行。我可以在Card
operator >
的定义中更改一些东西,以允许它与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);
}
相关文章:
- 为什么函数声明中允许 const?
- 在内存不足之前,我可以声明多少个 const 变量?
- 如何在声明为 const 的方法中更改类成员
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 可以使用<size_t>static_const(),std::as_const()或static_cast<const size_t>()来声明数组吗?
- 为什么必须将 const 添加到 constexpr 中才能进行字符串文字声明?
- 声明与 const 变量和成员函数相同的标识符
- 为什么我不能声明一个 constexpr 本地,而一个 const 一个工作?
- 类中的const声明
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- 为什么我们在这个函数声明中使用 const 和 & ?
- 不可变的全局对象应该声明为"const my_result_t BLAH"还是"extern const my_result_t BLAH;"?
- 为什么重载运算符>在参数声明 const 时不起作用?
- 如何在类中声明静态 const 结构元素
- 当我将 const int 声明/初始化为 5 时,它被初始化为一个大数字
- CPP主方法const声明
- 函数的Const声明
- 正在修改const声明对象上的可变对象的未定义行为
- 阅读复杂const声明的简单规则
- Const声明好奇