C++ 项目中枚举类上的迭代
我下面是对枚举的迭代C++ 项目中枚举类上的迭代,c++,c++11,iterator,code-separation,C++,C++11,Iterator,Code Separation,我下面是对枚举的迭代 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 C
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);}
问题是,在我的项目中,有许多cpp
和hpp
文件是单独编译的。编译器似乎需要直接访问运算符+++
的实现。如果我在hpp
中声明,然后在cpp
文件中实现,我将面临错误:
编译器警告:已使用内联函数“Color operator++(Color&)”,但从未定义
链接器错误:未定义对“operator++(指令类型&)”的引用
如果我在hpp
中直接定义它,我将面临另一个错误
多重定义
对于链接器中的
operator*
、begin
和end
。在4个函数前面添加inline
关键字将允许在标题中定义它们,而不会出现多个定义错误。例如:
inline COLOR operator*(COLOR c) {return c;}
或者您可以只在.h文件中包含原型,并在1.cpp文件中定义函数