C++ - enum vs. const vs. #define

2022-01-11 00:00:00 macros constants enumeration c++

本文结尾处: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.

相关文章