【问题标题】:write an overloaded operator for less-than-or-equal-to为小于或等于编写一个重载运算符
【发布时间】:2021-04-30 09:59:41
【问题描述】:
#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 行之间 此功能允许您比较两张卡。 尽管 A 的值为 1,但它是 实际上比所有其他卡的价值更大 确保你的超载小于或等于需要 考虑到这一点

我需要一些帮助来让 ace 比任何牌都更有价值

【问题讨论】:

  • C 没有重载的操作符,你为什么用那个标签?
  • 请不要发布带有行号的代码。这使得复制和粘贴到测试用例或答案中变得很困难。
  • 第一次发帖,感谢您的建议。
  • 添加 c 是我的错误
  • 你能用 14 作为 Ace 的值吗?

标签: c++


【解决方案1】:

添加额外的if 检查 A。

bool operator<=(Card &card) {
    if (card.value == 1) {
        return true;
    } else if (value == 1) {
        return false;
    } else {
        return value <= card.value;
    }
}

【讨论】:

    【解决方案2】:
    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 2022-09-24
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多