gpt4 book ai didi

c++ - 迭代项目中的枚举类

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:40 25 4
gpt4 key购买 nike

我正在关注 this question用于遍历枚举。

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);}

问题是在我的项目中,有很多cpphpp文件是分开编译的。编译器似乎需要直接访问 operator++ 的实现。如果我在 hpp 中声明然后在 cpp 文件中实现,我将面临错误:

compiler warning: inline function ‘Color operator++(Color&)’ used but never defined

linker error: undefined reference to `operator++(instruction_type&)'

如果我直接在hpp中定义它,我将面临另一个错误

multiple definition of ...

对于链接器中的operator*beginend

最佳答案

在您的 4 个函数前添加 inline 关键字将允许它们在 header 中定义,而不会出现多重定义错误。例如:

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

或者您可以只在 .h 文件中包含原型(prototype)并在 1 个 .cpp 文件中定义函数。

关于c++ - 迭代项目中的枚举类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32419612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com