c++ - 遍历常量枚举#define

标签 c++ loops enums constants

我的 C++ 代码中有一个 const 枚举,我想知道我是否可以循环遍历这些颜色,例如对这个枚举的每个成员的整数引用

const enum Colors
{
#define WHITE(alpha)            D3DCOLOR_ARGB(alpha, 255, 255, 255)//
#define RED(alpha)              D3DCOLOR_ARGB(alpha, 255, 000, 000)//
#define GREEN(alpha)            D3DCOLOR_ARGB(alpha, 000, 255, 000)//
#define BLUE(alpha)             D3DCOLOR_ARGB(alpha, 000, 000, 255)//
#define BLACK(alpha)            D3DCOLOR_ARGB(alpha, 000, 000, 000)//
#define PURPLE(alpha)           D3DCOLOR_ARGB(alpha, 125, 000, 255)//
#define GREY(alpha)             D3DCOLOR_ARGB(alpha, 44,44, 46)    //
#define YELLOW(alpha)           D3DCOLOR_ARGB(alpha, 255, 255, 000)//
#define ORANGE(alpha)           D3DCOLOR_ARGB(alpha, 255, 165, 000)//
#define DEEPSKYBLUE(alpha)      D3DCOLOR_ARGB(alpha, 30, 144, 255) //
#define CHOCOLATE2(alpha)       D3DCOLOR_ARGB(alpha, 238, 118, 33) //
};

此列表不完整 -> 我的枚举中有很多颜色

所以我真的想知道我是否可以使用可以循环遍历此枚举的键盘快捷键循环遍历所有颜色...

#define WHITE(alpha)            D3DCOLOR_ARGB(alpha, 255, 255, 255) = 1//<< something like that

我试过了,但这是不可能的......

最佳答案

首先,你不应该混合使用 #define 宏和 enum - 它们是完全不同的东西,你的代码等于 -

// Why was there `const`..?
enum Colors
{
    /* empty enum */
};

#define WHITE(alpha)            D3DCOLOR_ARGB(alpha, 255, 255, 255)//
#define RED(alpha)              D3DCOLOR_ARGB(alpha, 255, 000, 000)//
#define GREEN(alpha)            D3DCOLOR_ARGB(alpha, 000, 255, 000)//
#define BLUE(alpha)             D3DCOLOR_ARGB(alpha, 000, 000, 255)//
#define BLACK(alpha)            D3DCOLOR_ARGB(alpha, 000, 000, 000)//
#define PURPLE(alpha)           D3DCOLOR_ARGB(alpha, 125, 000, 255)//
#define GREY(alpha)             D3DCOLOR_ARGB(alpha, 44,44, 46)    //
#define YELLOW(alpha)           D3DCOLOR_ARGB(alpha, 255, 255, 000)//
#define ORANGE(alpha)           D3DCOLOR_ARGB(alpha, 255, 165, 000)//
#define DEEPSKYBLUE(alpha)      D3DCOLOR_ARGB(alpha, 30, 144, 255) //
#define CHOCOLATE2(alpha)       D3DCOLOR_ARGB(alpha, 238, 118, 33) //

所以,从现在开始,我将忽略 enum Colors 并讨论那些宏。


我建议您将值存储到数组中。

COLOR_TYPE colors[] = {
    WHITE(0),
    RED(0),
    ...
};

请注意 alpha 为零。由于数组只能存储值(不能存储宏函数),因此我应该用一些东西修复 alpha

然后,你可以像这样使用它:

color[42] & (alpha << 24)

如果觉得乱,可以再做一个宏

#define GET_COLOR(n, alpha) (color[(n)] & ((alpha) << 24))

或内联函数(..推荐)

inline COLOR_TYPE GetColor(int n, uint8_t alpha)
{
    return color[n] & (alpha << 24);
}

关于c++ - 遍历常量枚举#define,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444565/

相关文章:

c++ - 为什么我得到 "double free or corruption"?

c++ - 二元运算符的最佳命名空间是什么?

C++ 拉取信息并循环显示

C++如何使用其中也包含此类的类中的枚举

c++ - Emscripten编译qt应用不显示图像

c++ - 使用数组 C++ 进行组合

c - 如何在for循环中不按回车键填充数组

c++ - 如何将从文件读取的字符串关联到枚举值?

java - 使用 'valueOf' 检索枚举会抛出 RuntimeException - 改用什么?

c++ - 将数组指针访问从 C++ 转换为 Delphi