我偶然发现了 using namespace
指令的不寻常用法:
给定一个头文件WeirdNamespace.h
:
namespace WeirdNamespace
{
class WeirdClass
{
public:
int x;
void go();
};
}
我有一个匹配的“WeirdNamespace.cpp”:
#include "WeirdNamespace.h"
#include <iostream>
using namespace WeirdNamespace;
void WeirdClass::go()
{
std::cout << "Reached go?!" << std::endl;
}
该类的使用方式如下:
#include "WeirdNamespace.h"
int main(int argc, const char * argv[])
{
WeirdNamespace::WeirdClass c;
c.go();
}
到目前为止,我从未见过使用 using 指令来避免重新打开 cpp 文件中的命名空间或在方法名称前添加命名空间名称的前缀。该指令的正确用法吗?除了通常的 using namespace
警告之外,此场景是否存在任何特定的陷阱?
最佳答案
你可能会这样做:
namespace WN = WeirdNamespace;
WN::WeirdClass c;
现在,我得到了问题!以上是没有答案。
引用[7.3.4]使用指令
"During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace."
因此,您在源代码中的定义无需将其包含在命名空间中即可。
关于c++ - 使用 "using"指令来缩短函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18556714/