Nested NameSpaces in C++
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
?
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.
What is proper here?
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
.
If you're in ABC
you can skip the ABC
and just write 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
}
}
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.
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"
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
void f() {
ABC::XYZ::myobject = someValue;
// you *can* however use a using-declaration
using ABC::XYZ::myobject;
myobject = someValue;
}
精彩评论