Answer to Question #51262 in C++ for Zexy

Question #51262
Create a Card class with data fields for suit and card point value. Include a constructor that accepts arguments for the data fields. Also include overloaded greater-than and less-than operators for comparing card values. Create an overloaded == operator; two cards are equal if they have the same suit and value.
Randomly select two Card objects from a deck, making sure they are different.
(Appendix E contains information on random number generation.) Display both
Card objects and determine which is higher or whether they have the same value.
Save the file as DealTwoCards.cpp.
1
Expert's answer
2015-06-05T04:20:53-0400
Code. 
#include <iostream>
#include <cstdlib>
#include <ctime>
 
using namespace std;
 
class Card {
    int value;
    int suit;
public:
    Card(int value, int suit) {
       Card::value = value;
       Card::suit = suit;
    }
    // Overloading <<
    friend ostream& operator<<(ostream& os, const Card &c) {
        if (2 <= c.value && c.value <= 10) {
           os << c.value << " ";
        } else if (c.value == 1) {
           os << "ace ";
        } else if (c.value == 11) {
           os << "jack ";
        } else if (c.value == 12) {
           os << "queen ";
        } else if (c.value == 13) {
           os << "king ";
        }
 
        if (c.suit == 1) {
           os << "of Hearts";
        } else if (c.suit == 2) {
           os << "of Spades";
        } else if (c.suit == 3) {
           os << "of Diamonds";
        } else if (c.suit == 4) {
           os << "of Clubs";
        }
 
        return os;
    }
    // Overloading ==
    friend bool operator== (Card &c1, Card &c2) {
        return c1.value == c2.value && c1.suit == c2.suit;
    }
    // Overloading <
    friend bool operator< (Card &c1, Card &c2) {
        return c1.value < c2.value;
    }
    // Overloading >
    friend bool operator> (Card &c1, Card &c2) {
        return c1.value > c2.value;
    }
};
 
int main() {
    srand(time(NULL));
    int value = rand() % 13 + 1;
    int suit = rand() % 4 + 1;
    Cardc1(value, suit);
    value = rand() % 13 + 1;
    suit = rand() % 4 + 1;
    Cardc2(value, suit);
    while (c1 == c2) {
       value = rand() % 13 + 1;
       suit = rand() % 4 + 1;
       Card c1(value, suit);
       value = rand() % 13 + 1;
       suit = rand() % 4 + 1;
       Card c2(value, suit);
    }
    cout << c1 << endl;
    cout << c2 << endl;
    if (c1 > c2) {
       cout << "The first card isgreater than second.";
    } else {
       cout << "The second card is greaterthan first.";
    }
    return 0;
}
Input/Output.
queen of Diamonds
jack of Diamonds
The first card is greater than second.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS