#define 不尊重任何 C++ 范围。没有“本地”#define 这样的东西。它将在#undef-ed 之前一直有效。预处理器的宏机制就像大多数文本编辑器中的“查找和替换”功能一样;它不尊重文件的内容。
换句话说,如果您希望您的#define 在某个代码块中是本地的,您必须在该代码块的末尾#undef 它,因为宏不“理解”范围。
事实上,这是不鼓励使用宏的最大原因之一,除非它们在 C++ 中是绝对必要的。这就是为什么宏名称通常输入UPPER_CASE 以表明它实际上是一个宏。
实际上有很多针对您的具体情况的无宏解决方案。考虑以下几点:
namespace ReallyLongOuterNamespace
{
namespace ReallyLongInnerNamespace
{
class Foo {};
void Bar() {}
};
}
void DoThis()
{
// Too much typing!
ReallyLongOuterNamespace::ReallyLongInnerNamespace::Foo f;
ReallyLongOuterNamespace::ReallyLongInnerNamespace::Bar();
}
您可以使用命名空间别名:
void DoThis()
{
namespace rlin = ReallyLongOuterNamespace::ReallyLongInnerNamespace;
rlin::Foo f;
rlin::Bar();
}
你也可以使用typedefs:
void DoThis()
{
typedef ReallyLongOuterNamespace::ReallyLongInnerNamespace::Foo MyFoo;
MyFoo f;
}
您也可以使用using 声明:
void DoThis()
{
using ReallyLongOuterNamespace::ReallyLongInnerNamespace::Foo;
using ReallyLongOuterNamespace::ReallyLongInnerNamespace::Bar;
Foo f;
Bar();
}
你甚至可以使用以上的组合!
void DoThis()
{
namespace rlin = ReallyLongOuterNamespace::ReallyLongInnerNamespace;
typedef rlin::Foo MyFoo;
using rlin::Bar;
MyFoo f;
Bar();
}
对于Ogre::Real,它似乎是typedef 对应float 或double。您仍然可以使用命名空间别名、typedefs 和 using 声明以及 typedefs:
void UseOgre()
{
typedef Ogre::Real o_Real; // Yes, you can typedef typedefs.
using Ogre::Real;
/* Or, you can use:
namespace o = Ogre;
typedef o::Real o_Real;
using o::Real;
*/
// All equivalent
Ogre::Real r1;
o_Real r2;
Real r3;
o::Real r4;
}