Implementing a Deck of Cards in C++

2019-08-03 07:26发布

So I am trying to create a deck of cards and I am still kind of new to C++ and pointers so I have a few question

So I have Card class with getRank, getSuit, and comparison of two Card objects. They way I'm setting the deck is number 1-13 for the rank and 1-4 for the suit. So it's a simple compare by comparing one Card's rank+suit with another card's rank+suit.

So i initialize and declared the two arrays like this:

char Rank[13] = {1,...13};
char Suit[4] = ...

and my methods are like this:

char* getSuit(){ return Suit; }
char* getRank(){ return Rank; }
int Comp(Card *card) {
    if (rank+suit < card->rank+card->suit)
        return 1;
    else if...
    else ...
}

My question is, is it a bad idea to have a char array since i'm only storing integers? Later on i plan on converting these numbers to output "Three Spade" which is why i used char.

my other question is, does my get methods look right? The get methods, would it be returning the whole array or a index of the array, which is what I want. And am I using '->' correctly?

I still in the drawing process which is why i only have snippets of code

标签: c++ oop pointers
8条回答
我想做一个坏孩纸
2楼-- · 2019-08-03 08:13

A card is a poor candidate for a class - it has no behaviour, hence no methods. So it is better modelled as a struct. Cards are immutable (unless you're cheating), so const member data is indicated:

enum Suit {Hearts, Diamonds, Clubs, Spades};
enum Rank {A, K, Q, J, _10, _9, _8, _7, _6, _5, _4, _3, _2};

struct Card
{
    Card(Suit suit, Rank rank) : suit(suit), rank(rank) {}

    const Suit suit;
    const Rank rank;
};

If you can live with the syntax card.first instead of card.suit, you get this for free using the standard pair:

#include <utility>
typedef const std::pair<Suit, Rank> Card;

Card aceOfSpades(Spades, A);

Bonus: You also get reasonable == and < operators for free.

查看更多
够拽才男人
3楼-- · 2019-08-03 08:15

That's a bad idea because it's a waste of space. You only need to store one number, not all of them.

Also, you can implement the == operator instead of writing set of methods to do that, it would look more natural to use.

BTW: Re your logic - rank+suit is a criteria for comparison? Rank 9 of suit 4 is better than rank 10 of suit 2? I'm not sure what game it is that you're simulating, but usually the rank precedes the suits... But that depends on the actual requirements, of course, just saying....

Re your questions about using the -> and the get methods - look at the compiler errors when you get them. Yes, in the get methods, you return the array. But if you stop using arrays, and only store what you need - then the methods will be fine.

If you want to return string for whatever reason - you can map the integer index you store to the correct string in some static array, so that you won't store redundant strings in different instances of the classes.

查看更多
登录 后发表回答