C++ 中的嵌套命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3199139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested NameSpaces in C++
提问by jDOG
I am confused what to do when having nested namespaces and declarations of objects.
我很困惑在嵌套命名空间和对象声明时该怎么做。
I am porting some code that links against a static library that has a few namespaces.
我正在移植一些链接到具有几个命名空间的静态库的代码。
Example of what I am talking about:
我正在谈论的示例:
namespace ABC {
namespace XYZ {
//STUFF
}
}
In code what do I do to declare an object that is in namespace XYZ
?
在代码中,我该怎么做才能声明命名空间中的对象XYZ
?
if I try:
如果我尝试:
XYZ::ClassA myobject;
or:
或者:
ABC::XYZ::ClassA myobject;
or:
或者:
ABC::ClassA myobject;
I get
我得到
does not name a type
不命名类型
errors, even though ClassA
definitely exists.
错误,即使ClassA
肯定存在。
What is proper here?
这里什么是合适的?
回答by ereOn
It depends on the namespace you already are:
这取决于您已经是的命名空间:
If you're in no namespace or another, unrelated namespace, then you have to specify to whole path ABC::XYZ::ClassA
.
如果您不在名称空间或其他不相关的名称空间中,则必须指定为整个路径ABC::XYZ::ClassA
。
If you're in ABC
you can skip the ABC
and just write XYZ::ClassA
.
如果你在,ABC
你可以跳过ABC
,直接写XYZ::ClassA
.
Also, worth mentioning that if you want to refer to a function which is not in a namespace (or the "root" namespace), you can prefix it by ::
:
另外,值得一提的是,如果您想引用不在命名空间(或“根”命名空间)中的函数,您可以添加前缀::
:
Example:
例子:
int foo() { return 1; }
namespace ABC
{
double foo() { return 2.0; }
void bar()
{
foo(); //calls the double version
::foo(); //calls the int version
}
}
回答by Johannes Schaub - litb
If myobject
is declared in that namespace and you want to declare it again (for defining it), you do it by prefixing its name, not its type.
如果myobject
在该命名空间中声明并且您想再次声明它(用于定义它),则可以通过为其名称而不是其类型添加前缀来实现。
ClassA ABC::XYZ::myobject;
If its type is declared in that namespace too, you also need to prefix the name of the type
如果它的类型也在该命名空间中声明,则还需要在类型名称前加上前缀
ABC::XYZ::ClassA ABC::XYZ::myobject;
It's rarely needed to redeclare an object like that. Often the first declaration of an object is also its definition. If you want to first declare the object, you have to do it in that namespace. The following declares and defines "myobject"
很少需要像这样重新声明一个对象。通常对象的第一个声明也是它的定义。如果要首先声明对象,则必须在该命名空间中进行。以下声明并定义了“myobject”
namespace ABC {
namespace XYZ {
ClassA myobject;
}
}
If you have defined in object like this, you refer to it by saying ABC::XYZ
. You don't have to "declare" that object somehow in order to use it locally
如果您在对象中定义了这样的内容,您可以通过说ABC::XYZ
. 您不必以某种方式“声明”该对象即可在本地使用它
void f() {
ABC::XYZ::myobject = someValue;
// you *can* however use a using-declaration
using ABC::XYZ::myobject;
myobject = someValue;
}