簡體   English   中英

訪問類 C++ 中定義的枚舉

[英]Accessing Enum defined within a class C++

我有以下代碼:

// Piece.h
class Piece 
{

  public:
    enum class Color {BLACK, WHITE};

    Piece();
    Piece(int x, int y, Piece::Color color);
    

  private:
    int m_x;
    int m_y;
    Piece::Color m_color;
    static const int UNINITIALIZED = -1;

};

如何從方法函數訪問枚舉:(嘗試)

// Piece.cpp
Piece::Piece() :
  m_x(Piece::UNINITIALIZED),
  m_y(Piece::UNINITIALIZED),
  m_color(Piece::Color BLACK) // PROBLEM
{}

Piece::Piece(int x, int y, Piece::Color color) :
  m_x(x),
  m_y(y),
  m_color(color)
{}

問題:

Piece.cpp: In constructor ‘Piece::Piece()’:
Piece.cpp:8:24: error: expected primary-expression before ‘BLACK’
    8 |   m_color(Piece::Color BLACK)

我是 C++ 新手,所以這可能不是好的代碼實踐,但我通常想知道如何實現這一點(並且也理解為什么我不應該這樣寫,如果它實際上是不好的做法)

謝謝

您可以像訪問任何靜態成員一樣訪問枚舉(類)成員。 在這種情況下, Piece::Color::BLACK


在構造函數中,您可以省略“Piece”部分,只需編寫以下內容:

Piece::Piece() :
  m_x(UNINITIALIZED),
  m_y(UNINITIALIZED),
  m_color(Color::BLACK)
{}

關於您暗示這是不好的做法:不是。 您可能可以將 int 更改為constexpr而不僅僅是const ,但是無論您嘗試對 enum 值做什么都很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM