gpt4 book ai didi

C++ 枚举和编译器依赖

转载 作者:太空狗 更新时间:2023-10-29 20:06:43 25 4
gpt4 key购买 nike

我目前有一个带有枚举的代码,其中设置了一个值,其余的由编译器使用先前的值 +1 设置,我希望如此。

此功能是否依赖于枚举类型编译器,下面通过示例进行说明。

enum FUNC_ERROR_CODE    
{
FUNC_SUCCESS,
FUNC_ERROR_1 = 24,
FUNC_ERROR_2,
FUNC_ERROR_3
}

无论使用何种编译器,假设 FUNC_ERROR_2 的值为 25 而 FUNC_ERROR_3 的值为 26 是否安全。

我正在对此进行编码,因为函数可以返回一个整数值,0 总是成功,任何其他值都可以表示失败。

最佳答案

可以安全地假设:

  • 枚举声明 [dcl.enum]

    The identifiers in an enumerator-list are declared as constants, and can appear wherever constants are required. An enumerator-definition with = gives the associated enumerator the value indicated by the constant-expression. The constant-expression shall be of integral or enumeration type. If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.

但是如果您有类型安全的枚举:使用它!不要依赖与整数之间的转换。

关于C++ 枚举和编译器依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6492612/

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