访问在C+&#x2B类中定义的枚举
我有以下代码:
// 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您会访问枚举(类)成员,例如您将访问任何静态成员。
pice :: 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:
Regarding your hint about this being bad practice: It isn't. You could probably change the int to be a
constexpr
instead of justconst
, but whatever you are trying to do with the enum value is totally fine.