使用“使用"表示“使用".指令以缩短功能定义 [英] Using "using" directive to shorten function definition
问题描述
我偶然发现using namespace
指令对我来说是不寻常的:
I have stumbled upon an unusual to me usage of using namespace
directive:
给出头文件WeirdNamespace.h
:
namespace WeirdNamespace
{
class WeirdClass
{
public:
int x;
void go();
};
}
我有一个匹配的'WeirdNamespace.cpp`:
I have a matching '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();
}
直到现在,我还从未见过用于避免重新打开cpp文件中的名称空间或使用名称空间名称作为前缀的方法名称的using指令.指令的正确用法吗?除了常见的using namespace
注意事项外,是否存在针对此场景的陷阱?
Until now I have never seen the using directive used to avoid reopening the namespace in the cpp file or prefixing method names with the namespace name. Is it a correct usage of the directive? Are there any pitfalls specific to this scenario, except for the usual using namespace
caveats?
推荐答案
您可以这样做:
namespace WN = WeirdNamespace;
WN::WeirdClass c;
现在,我明白了!上面没有答案.
引用自[7.3.4]使用指令
Quoting from [7.3.4] Using directive
在非限定名称查找(3.4.1)期间,名称看起来像它们 在最近的封闭命名空间中声明,该命名空间包含两个 using指令和指定的名称空间."
"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."
因此可以在源代码中定义而不将其包含在名称空间中.
Hence your definition in the source without enclosing it in the namespace is fine.
这篇关于使用“使用"表示“使用".指令以缩短功能定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!