为什么不重载运算符>当参数被声明为const时工作?

时间:2017-07-21 21:07:28

标签: c++ operator-overloading

我正在编写一个模拟特技纸牌游戏的程序。在确定诀窍获胜者的函数中,我创建了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,我将其用作我的排序谓词,代码将按预期编译并执行。我可以在Card operator >的定义中更改某些内容,以便使用card1card2 const进行编译,或者我应该只留下足够的好吗?

1 个答案:

答案 0 :(得分:4)

 @Override

    public void configure(HttpSecurity http) throws Exception {
         http.requestMatcher(new OAuthRequestedMatcher())
                .authorizeRequests()
                 .antMatchers(HttpMethod.OPTIONS).permitAll()
                    .anyRequest().authenticated();
    }

    private static class OAuthRequestedMatcher implements RequestMatcher {
        public boolean matches(HttpServletRequest request) {
            String auth = request.getHeader("Authorization");
            boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer");
            boolean haveAccessToken = request.getParameter("access_token")!=null;
   return haveOauth2Token || haveAccessToken;
        }
    }

这需要声明为const成员函数。不能在bool operator > (const Card& compareTo) { return (rank > compareTo.rank); } 个对象上调用没有附加到其签名的const限定符的成员函数,因为没有此限定符,编译器不确定对该对象没有进行任何更改在该函数中的状态 - 如果在签名中包含const,编译器将强制执行此合同,如果您尝试更改此函数内对象的状态,则无法编译。

更正后的代码如下所示:

const