C++ Enum Values

C++ Enum Values

本文关键字:Values Enum C++      更新时间:2023-10-16

我正试图通过转换几个Java类来学习c++,我之前做了一段时间。它们代表一张扑克牌和一副扑克牌。我使用enum作为值和套装:

enum Suits{SPADES, CLUBS, HEARTS, DIAMONDS};
enum Values{TWO, THREE, FOUR, FIVE, 
            SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE};

在我的JavaC++卡类中,我有方法:getValue()getSuit(),它们分别返回值和花色。

我的Java DeckofCards类非常简单:

public class DeckofCards {
private Card card; 
private String value;
private String suit;
private List<Card> deck = new ArrayList<Card>();
//DeckofCards constructor
public DeckofCards(){
    for (Suits s : Suits.values()) {
        for(Values v : Values.values()){
            card = new Card(v,s);
            deck.add(card);
        }  
    }
}
//shuffles the deck
public void shuffleDeck(){
    Collections.shuffle(deck);
}
//prints the deck of cards
public void printDeck(){
    for(int i = 0; i<deck.size(); i++){
        card = deck.get(i);
        value = card.getValue().toString();
        suit = card.getSuits().toString();
        System.out.println(value + " of " + suit);
    }
}
//draws a card from the deck
public Card drawCard(){
    try{
        card = deck.get(0);
        deck.remove(0);
        //return card;
    }
    catch(IndexOutOfBoundsException e){
        System.err.println("Deck is empty");
        System.exit(0);
    }
    return card;
}
} 

我的问题是在c++中实现printDeck()方法,特别是获得enum值的字符串表示。我知道我不能简单地做getValue().toString(),所以我的想法在做了一些关于这个问题的研究之后,是使两个std::string[]看起来与两个enum s一样,然后使用getValue()getSuit()来生成一个int(因为这似乎是行为),并将其传递到数组中以获得字符串表示。

然而,我现在认为它可能是更好的添加两个方法在我的卡类:

std::string getValue(int i), suit

并使用case语句返回基于intstring值,以便其他类可以轻松获得字符串表示。这似乎是多余的。谁能就如何做到这一点提供一些建议?

您可以使用新的c++ 11枚举类(即有作用域的枚举),并定义一个函数,该函数接受这样的枚举类作为输入参数,并返回输入枚举值的相应字符串表示形式。

例如:

#include <assert.h>     // For assert()
#include <iostream>     // For console output
#include <string>       // For std::string
enum class Suits {
    SPADES, CLUBS, HEARTS, DIAMONDS
};
std::string toString(Suits s) {
    switch (s) {
    case Suits::SPADES:     return "Spades";
    case Suits::CLUBS:      return "Clubs";
    case Suits::HEARTS:     return "Hearts";
    case Suits::DIAMONDS:   return "Diamonds";
    default:
        assert(false);
        return "";
    }
}
int main() {
    std::cout << toString(Suits::CLUBS) << std::endl;
}

您可以对Values枚举做类似的事情。

在c++中,枚举没有元数据,所以如果你想要一个字符串版本,你需要自己编写一个转换器。

我可能会这样做,这不能编译,但你有一个粗略的图片

enum Suit { ... }
enum Values { ... }
Class card {
public:
   static std::string getText(Suite s) { switch(s) case CLUBS: return "clubs"; ... }
   static std::string getText(Colour c) { switch(c) case ONE: return "one"; ... }
   card(Suite s, Colour c) : mSuite(s), mColour(c) {}
   std::string getText() const {
       stringstream ss;
       ss << getText(mColour) << " of " << getText(mSuits);
       return ss.str();
   }
};
ostream& operator<<(ostream& stream, const card& c) {
    stream << c.getText();
}