如何访问结构和枚举成员形成一类

How to access struct and enum members form a class?

本文关键字:一类 枚举成员 结构 何访问 访问      更新时间:2023-10-16

这似乎是一个简单的解决方案的三词问题,但对我来说,这是一个问题。我在说的是这个代码:

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类型中),因此当您引用符号值时,您不会遇到错误。这与minespaddingHeightpaddingWidth不同。下面的代码对我有用:

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中提取的更好的提取物。

为您的扫雷器编码愉快;)