Search code examples
c++classc++11variablesinitialization

Class Initializer checking for certain input


I have a Class in a header file and I am trying to implement the initializing given a certain input. So my header file excluding headers looks something like this:

class Card {
public:
  // rank and suit names
  static constexpr const char* const RANK_TWO = "Two";
  static constexpr const char* const RANK_THREE = "Three";
  static constexpr const char* const RANK_FOUR = "Four";
  static constexpr const char* const RANK_FIVE = "Five";
  static constexpr const char* const RANK_SIX = "Six";
  static constexpr const char* const RANK_SEVEN = "Seven";
  static constexpr const char* const RANK_EIGHT = "Eight";
  static constexpr const char* const RANK_NINE = "Nine";
  static constexpr const char* const RANK_TEN = "Ten";

  static constexpr const char* const SUIT_SPADES = "Spades";
  static constexpr const char* const SUIT_HEARTS = "Hearts";
  static constexpr const char* const SUIT_CLUBS = "Clubs";
  static constexpr const char* const SUIT_DIAMONDS = "Diamonds";

Card();

Card(const std::string &rank_in, const std::string &suit_in);

private:
  std::string rank;
  std::string suit;
};

For the implementation of the second initializer I have this so far.

Card::Card(const std::string &rank_in, const std::string &suit_in){

    this->rank = rank_in;
    this->suit = suit_in;
}

To check if my rank_in and suit_in match one of the variables inside the class, do I need to check each one individually or is there a way to do this more efficiently? Thanks in advance the help is much appreciated


Solution

  • or is there a way to do this more efficiently?

    yes, you can explode the new c++11 features:

    class K 
    {
        public:
            enum class R
            {
                TWO,
                THREE,
                FOUR
            };
            enum class Su
            {
                S,
                H,
                C,
                D
            };
            K(const R someR, const Su someSu);
        private:
            R r;
            Su su;
    };
    #endif /* K_H */
    
    K::K(const R someR, const Su someSu): r{someR}, su{someSu}
    {
    
    }
    

    with this approach you are avoiding the user of the class to make mistakes by mixing the types of your parameters in the constructor...