如何访问结构和枚举成员形成一类
How to access struct and enum members form a class?
这似乎是一个简单的解决方案的三词问题,但对我来说,这是一个问题。我在说的是这个代码:
class MainWindow
{
public:
enum class Difficulty
{
Beginner,
Intermediate,
Advanced
};
struct DifficultyLevelsProperties
{
struct BeginnerProperties
{
const int PADDING_HEIGHT = 9;
const int PADDING_WIDTH = 9;
const int MINES = 10;
};
struct IntermediateProperties
{
const int PADDING_HEIGHT = 16;
const int PADDING_WIDTH = 16;
const int MINES = 40;
};
struct AdvancedProperties
{
const int PADDING_HEIGHT = 16;
const int PADDING_WIDTH = 40;
const int MINES = 99;
};
};
MainWindow();
~MainWindow();
private:
Difficulty difficulty = Difficulty::Beginner;
int mines = DifficultyLevelsProperties::BeginnerProperties.MINES;
int paddingHeight = DifficultyLevelsProperties::BeginnerProperties.PADDING_HEIGHT;
int paddingWidth = DifficultyLevelsProperties::BeginnerPropertiesPADDING_WIDTH;
我要实现的目标很明显。我尝试使用"。和" ::"操作员在不同的地方或使其成为静态的操作员,但我仍然无法做到正确。我要么得到"困难"不是类或名称空间的错误,要么是"在'之前预期的主表达'。令牌"。请帮忙。谢谢!
我正在关注您的代码的问题是您正在尝试访问未实例化的值。我的意思是,当您尝试将值分配给mines
属性时,您是在引用声明,而不是实例化的值,因为没有任何实例化。
当您声明某些内容时,您正在解释如何在不分配任何值或行为的情况下结构内存。
枚举之所以可以使用,是因为符号名称被映射到一个值中(旧时代它被直接映射到int类型中),因此当您引用符号值时,您不会遇到错误。这与mines
,paddingHeight
和paddingWidth
不同。下面的代码对我有用:
class MainWindow
{
public:
enum class Difficulty
{
Beginner,
Intermediate,
Advanced
};
struct DifficultyLevelsProperties
{
struct BeginnerProperties
{
const int PADDING_HEIGHT = 9;
const int PADDING_WIDTH = 9;
const int MINES = 10;
} beginner;
struct IntermediateProperties
{
const int PADDING_HEIGHT = 16;
const int PADDING_WIDTH = 16;
const int MINES = 40;
} intermediate;
struct AdvancedProperties
{
const int PADDING_HEIGHT = 16;
const int PADDING_WIDTH = 40;
const int MINES = 99;
} advanced;
} levelProperties;
MainWindow();
~MainWindow();
private:
Difficulty difficulty = Difficulty::Beginner;
int mines = levelProperties.beginner.MINES;
int paddingHeight = levelProperties.beginner.PADDING_HEIGHT;
int paddingWidth = levelProperties.beginner.PADDING_WIDTH;
};
顺便说一句,从坚实的原理的角度来看,设计可能不是最好的。您将处理属性与MainWindow混合。也许是从MainWindow中提取的更好的提取物。
为您的扫雷器编码愉快;)
相关文章:
- 枚举成员与静态 int 成员?
- 从类访问枚举成员
- 枚举成员不是类型错误
- std::映射键作为模板化结构与枚举成员
- 设置类的枚举成员无效地使用"枚举"
- 如何访问结构和枚举成员形成一类
- 是否可以在 constexpr 函数中遍历枚举成员,因此值为 constexpr
- 获取 [枚举成员?] 的封闭类型
- 如何使用 SWIG 枚举枚举成员
- 通过int值访问枚举成员
- '='应初始化所有枚举成员或仅初始化第一个枚举成员;
- 为什么可以获取此枚举成员值,而不必先深入研究嵌套枚举
- 将具有枚举成员的非托管结构封送到 C#
- 为类模板的枚举成员定义 std::hash
- 缩短C++枚举成员的路径(使用 typedef 或 typename),以用作模板参数
- C++类枚举成员变量
- 检查是否已定义枚举成员
- 为什么要使用这段代码来获取枚举成员的数量?
- 使用枚举成员模板化成员函数
- 使用咬运算符了解枚举成员的初始化