如果我在命名空间中使用一些宏定义,那么为什么它们应该在命名空间之外工作?检查此代码,例如:
#include <bits/stdc++.h>
namespace foo {
#define a x*2
int f(int x) {
return a;
}
}
int main() {
int a = 50;
std::cout << a << endl;
std::cout << foo::f(4) << endl;
return 0;
}
在这里,我从未使用命名空间foo编写过代码。但是仍然无法编译此代码,因为在尝试声明int a时,它会受到先前定义的a的干扰。但是为什么要这样呢?
“ ...当试图声明int a时,它会受到先前定义的a的干扰。但是为什么要这样呢?”
该#define
语句由不具有名称空间(或任何其他c ++语言构造)概念的c / c ++预处理器解释。
如果要限制定义的范围,请使用#undef
指令:
namespace foo {
#define a x*2
int f(int x) {
return a;
}
#undef a
// ^^^^^^^^
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句