命名空间作用域问题

Namespace Scope Question

本文关键字:问题 作用域 命名空间      更新时间:2023-10-16

我有一个关于名称空间作用域的快速问题:

  1. 我有两个命名空间,A和B,其中B嵌套在A中。
  2. 我在a中声明了一些类型定义。
  3. 我在B中声明了一个类(它在a中)

要从B内部访问类型定义(在A中声明),我是否需要执行"using namespace A;"

ie:

B.hpp:

using namespace A;
namespace A {
namespace B {
  class MyClass {
    typedeffed_int_from_A a;
  };
}
}

这似乎是多余的…这是正确的吗?

要从B内部访问类型定义(在A中声明),我是否需要执行"using namespace A;"


但是,如果在命名空间B中定义了与您的typedef同名的其他符号的typedef,那么您需要这样写:

A::some_type a;

让我们做一个简单的实验来理解这个。

考虑以下代码:(必须读取注释)
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;
}
输出:

f(char*)
f(int)

证明mchar*, nint,符合预期或预期。

在线演示:http://ideone.com/abXc8

不,您不需要using指令;由于B嵌套在A内部,所以A的内容在B内部时也在作用域中。