#define
能否“覆盖”const 变量,反之亦然?还是会导致编译错误?
//ONE
#define FOO 23
const int FOO = 42;
//TWO
const int FOO = 42;
#define FOO 23
在 42 或 23 这两种情况下,FOO 的值是多少?
最佳答案
第一个会给出编译错误。从定义的角度来看,宏是可见的。
也就是说,第一个相当于:
//ONE
#define FOO 23
const int 23= 42; //which would cause compilation error
第二个是这样的:
//TWO
const int FOO = 42;
#define FOO 23 //if you use FOO AFTER this line, it will be replaced by 23
因为宏是哑的,在 C++ 中 const
和 enum
优于宏。在这里查看我的回答,我在其中解释了为什么宏不好,const
和 enum
是更好的选择。
关于c++ - #define 与 const 声明的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7370535/