简体   繁体   English

迭代项目中的枚举类

[英]Iteration over enum class in a project

I am following this question for iterating over an enum.我正在关注这个问题以迭代枚举。

enum class COLOR
{
    Blue,
    Red,
    Green,
    Purple,
    First=Blue,
    Last=Purple
};

COLOR operator++( COLOR& x ) { return x = (COLOR)(((int)(x) + 1)); }

COLOR operator*(COLOR c) {return c;}

COLOR begin(COLOR r) {return COLOR::First;}
// end iterator needs to return one past the end!
COLOR end(COLOR r)   {return COLOR(int(COLOR::Last) + 1);}

The problem is that in my project, there are many cpp and hpp files which are compiled separately.问题是在我的项目中,有很多单独编译的cpphpp文件。 It seems the compiler needs to have direct access to implementation of operator++ .似乎编译器需要直接访问operator++实现。 If I declare in a hpp and then implement in cpp file, I will face with error:如果我在hpp声明然后在cpp文件中实现,我将面临错误:

compiler warning: inline function 'Color operator++(Color&)' used but never defined编译器警告:使用内联函数“颜色运算符++(颜色&)”但从未定义

linker error: undefined reference to `operator++(instruction_type&)'链接器错误:未定义对`operator++(instruction_type&)'的引用

If I define it directly in hpp , I will face with another error如果我直接在hpp定义它,我将面临另一个错误

multiple definition of ... ...的多重定义

for operator* , begin , and end in linker.对于operator*beginend在链接器中。

Adding the inline keyword in front of your 4 functions will allow them to be defined in the header without the multiple definition errors.在您的 4 个函数前面添加inline关键字将允许它们在标题中定义而不会出现多个定义错误。 For example:例如:

inline COLOR operator*(COLOR c) {return c;}

Or you can include just the prototype in the .h file and define the functions in 1 .cpp file.或者,您可以仅在 .h 文件中包含原型并在 1 个 .cpp 文件中定义函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM