访问在C+&#x2B类中定义的枚举

发布于 2025-02-04 07:42:01 字数 885 浏览 1 评论 0原文

我有以下代码:

// 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 ++的新手,所以这可能不是很好的代码实践,但是我通常想知道如何实现这一目标不好的练习)

谢谢

I have the following code:

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

};

How do I access the enum from the method functions:
(attempt)

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

The Problem:

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

I'm new to C++ so this might not be good code practice, but I would generally like to know how to achieve this (and also understand why I shouldn't write like this, if it is in fact bad practice)

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自演自醉 2025-02-11 07:42:01

您会访问枚举(类)成员,例如您将访问任何静态成员。
pice :: color :: black在这种情况下。


在构造函数中,您可以省略“零件”部分,然后写下以下内容:

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

关于您的暗示是不好的做法:不是。您可能可以将int更改为constexpr,而不是const,但是无论您尝试使用枚举值的方法是完全可以的。

You access enum (class) members like you would access any static member.
Piece::Color::BLACK in this case.


In the constructor, you could omit the "Piece" part and just write the following:

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

Regarding your hint about this being bad practice: It isn't. You could probably change the int to be a constexpr instead of just const, but whatever you are trying to do with the enum value is totally fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文