繁体   English   中英

为小于或等于编写一个重载运算符

[英]write an overloaded operator for less-than-or-equal-to

#include <iostream>

using namespace std;

class Card
{
    private:
        // suit contains values 1-4, to represent suits below
        // 1 - Diamonds, 2 - Hearts, 3 - Clubs, 4 - Spades
        int suit;
        // value contains values 1 - 13
        // Ace - 1, 2-10, J - 11, Q - 12, K - 13
        int value;
    public:
        Card() {}

        Card(int s, int v)
        {
            suit = s;
            value = v;
        }

        string as_string()
        {

            return to_string(suit) + " of " + to_string(value);
        }

// =================================================================

        bool operator<=(Card & card)    // <--- Line 29
        {
            if(value<=(card.value))
            {
                return true;
            }
            else
            {
                return false;
            }
        }                              // <--- Line 39

// =================================================================

        friend ostream & operator<<(ostream & out, Card & test1)
        {
            out << test1.as_string();

            return out;
        }


};

int main()
{
    Card test1(1,1);   // Ace of Diamonds
    Card test2(1,10);  // 10 of Diamonds

    cout << test1 << endl;    // should show "Ace of Diamonds"

    if (test2 <= test1)
    {
        // should show "Ace of Diamonds beats 10 of diamonds"
        cout << test1 << " beats " << test2 << endl;
    }
    else
    {
        cout << test2 << " beats " << test1 << endl;
    }
    return 0;
}

在第 29 行和第 39 行之间,此 function 允许您比较两张卡。 尽管 A 的值是 1,但它实际上比所有其他牌的价值都大

我需要一些帮助来使 ace 的价值高于任何牌

添加额外的if检查 A。

bool operator<=(Card &card) {
    if (card.value == 1) {
        return true;
    } else if (value == 1) {
        return false;
    } else {
        return value <= card.value;
    }
}
bool operator<=(Card const & card) const{
  auto proj=[](auto x){return (x==1)?13:x;};
  return proj(value)<=proj(card.value);
}

甚至

int projection()const{((value+12)%14);}
bool operator<=(Card const& card) const {
  return projection()<=card.projection();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM