C++ - enum vs. const vs. #define(C++ - enum vs. const vs. #define)
问题描述
本文结尾处:http://www.learncpp.com/cpp-tutorial/45-enumerated-types/,它提到了以下内容:
At the end of the article here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/, it mentions the following:
最后,与常量变量一样,枚举类型会显示在调试器中,在这方面它们比#defined 值更有用.
上面的粗体字是怎么实现的?
How is the bold sentence above achieved?
谢谢.
推荐答案
考虑一下这段代码,
#define WIDTH 300
enum econst
{
eWidth=300
};
const int Width=300;
struct sample{};
int main()
{
sample s;
int x = eWidth * s; //error 1
int y = WIDTH * s; //error 2
int z = Width * s; //error 3
return 0;
}
显然每次乘法都会导致编译错误,但请查看 GCC 如何为每个乘法错误生成消息:
Obviously each multiplication results in compilation-error, but see how the GCC generates the messages for each multiplication error:
prog.cpp:19:错误:不匹配‘eWidth * s’中的‘operator*’
prog.cpp:20:错误:不匹配‘300 * s’中的‘operator*’
prog.cpp:21:错误:不匹配‘Width * s’中的‘operator*’
prog.cpp:19: error: no match for ‘operator*’ in ‘eWidth * s’
prog.cpp:20: error: no match for ‘operator*’ in ‘300 * s’
prog.cpp:21: error: no match for ‘operator*’ in ‘Width * s’
在错误消息中,您没有看到您已#defined 的宏WIDTH,对吧?这是因为当 GCC 尝试编译该行对应于第二个错误时,它没有看到 WIDTH,它只看到 300,因为在 GCC 编译该行之前,预处理器有 已经将 WIDTH 替换为 300.另一方面,enum eWidth 和 const 宽度.
In the error message, you don't see the macro WIDTH which you've #defined, right? That is because by the time GCC makes any attempt to compile the line corresponds to second error, it doesn't see WIDTH, all it sees only 300, as before GCC compiles the line, preprocessor has already replaced WIDTH with 300. On the other hand, there is no any such thing happens with enum eWidth and const Width.
在这里自己查看错误:http://www.ideone.com/naZ3P
另外,请阅读 Scott Meyers 的 Effective C++ 中的 Item 2 : Prefer consts, enums, and inlines to #defines.
Also, read Item 2 : Prefer consts, enums, and inlines to #defines from Effective C++ by Scott Meyers.
这篇关于C++ - enum vs. const vs. #define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ - enum vs. const vs. #define
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
