簡體   English   中英

當參數聲明為const時,為什么不重載operator>會起作用?

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

我正在編寫一個模擬花式紙牌游戲的程序。 在確定花樣贏家的函數中,我創建一個listlist所有花色匹配其領導花色的花色。 然后我那種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 如果我宣布card1card2作為非const在我為我的排序謂詞使用lambda函數,代碼編譯與預期相符。 是否可以更改Cardoperator >的定義, card2聲明為const card1card2進行編譯,還是我應該一個人呆着?

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

這需要聲明為const成員函數。 沒有在其簽名上附加const限定符的成員函數無法在const對象上調用,因為如果沒有此限定符,編譯器肯定無法確定該函數中的對象狀態沒有任何變化-如果您如果在簽名中包含const ,則編譯器將強制執行此合同,並且如果您嘗試更改此函數內對象的狀態,則編譯失敗。

更正后的代碼如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM