[英]Iteration over enum class in a project
我正在關注這個問題以迭代枚舉。
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
文件。 似乎編譯器需要直接訪問operator++
實現。 如果我在hpp
聲明然后在cpp
文件中實現,我將面臨錯誤:
編譯器警告:使用內聯函數“顏色運算符++(顏色&)”但從未定義
鏈接器錯誤:未定義對`operator++(instruction_type&)'的引用
如果我直接在hpp
定義它,我將面臨另一個錯誤
...的多重定義
對於operator*
、 begin
和end
在鏈接器中。
在您的 4 個函數前面添加inline
關鍵字將允許它們在標題中定義而不會出現多個定義錯誤。 例如:
inline COLOR operator*(COLOR c) {return c;}
或者,您可以僅在 .h 文件中包含原型並在 1 個 .cpp 文件中定義函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.