c++ - 类初始值设定项检查特定输入

标签 c++ class c++11 variables initialization

我的头文件中有一个类,我正在尝试实现给定特定输入的初始化。 所以我的头文件(不包括标题)看起来像这样:

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;
};

对于第二个初始化器的实现,到目前为止我已经做到了。

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

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

要检查我的rank_in和suit_in是否与类内的变量之一匹配,我是否需要单独检查每个变量,或者是否有一种方法可以更有效地做到这一点?预先感谢您的帮助,非常感谢

最佳答案

or is there a way to do this more efficiently?

是的,您可以爆炸新的 c++11 功能:

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}
{

}

使用这种方法,您可以通过在构造函数中混合参数的类型来避免类的用户犯错误...

关于c++ - 类初始值设定项检查特定输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52968827/

相关文章:

c++ - 为什么 C++ 引入了单独的 std::latch 和 std::barrier?

python - 如何使用用户定义的类对象作为 networkx 节点?

C++ 发送派生指针作为参数

c++ - 将 const auto & 转换为迭代器

c++ - 如何使用 C++11 使用语法对函数指针进行类型定义?

c++ - 如何根据模板类的基类专门化成员函数

c++ - 获取 std::array 的第二个参数(大小)作为函数参数

c++ - 关于C++头文件的简单问题

c++ - Sum C++ 返回的垃圾值

PHP 类/OOP : When to "reference" a class within a class vs extend a class?