I have a quick question about namespace scope:
- I have two namespaces, A and B, where B is nested inside A.
- I开发者_高级运维 declare some typedefs inside A.
- I declare a class inside B ( which is inside A )
To access the typedefs (declared in A), from inside B, do I need to do "using namespace A;"
ie:
B.hpp:
using namespace A;
namespace A {
namespace B {
class MyClass {
typedeffed_int_from_A a;
};
}
}
This seems redundant... Is this correct?
To access the typedefs (declared in A), from inside B, do I need to do "using namespace A;"
No.
However if there is a typedef or some other symbol with same name as your typedef, defined in the namespace B
, then you need to write this:
A::some_type a;
Lets do a simple experiment to understand this.
Consider this code: (must read the comments)
namespace A
{
typedef int some_type; //some_type is int
namespace B
{
typedef char* some_type; //here some_type is char*
struct X
{
some_type m; //what is the type of m? char* or int?
A::some_type n; //what is the type of n? char* or int?
};
void f(int) { cout << "f(int)" << endl; }
void f(char*) { cout << "f(char*)" << endl; }
}
}
int main() {
A::B::X x;
A::B::f(x.m);
A::B::f(x.n);
return 0;
}
Output:
f(char*)
f(int)
That proves that type of m
is char*
and type of n
is int
as expected or intended.
Online Demo : http://ideone.com/abXc8
No, you don't need a using
directive; as B
is nested inside of A
, the contents of A
are in scope when inside B
.
精彩评论