c++ - 命名空间范围问题

标签 c++ namespaces

我有一个关于命名空间范围的快速问题:

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

要从 B 内部访问 typedef(在 A 中声明),我是否需要执行“使用命名空间 A;”

即:

B.hpp:

using namespace A;

namespace A {
namespace B {

  class MyClass {

    typedeffed_int_from_A a;
  };

}
}

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

最佳答案

To access the typedefs (declared in A), from inside B, do I need to do "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)

证明 mtypechar* 并且 typen 是预期或预期的 int

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

关于c++ - 命名空间范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5624658/

相关文章:

c++ - 将指向成员函数的指针传递给单独的线程

python - 使用装饰器将变量带入装饰函数命名空间

c++ - 未在命名空间中声明和定义的命名空间的类的 friend

.Net 命名表(命名空间)问题

jquery - 添加命名空间后 Bootstrap 模式不起作用

c++ - 为函数设计接口(interface),强制用户(客户端)提供 >= 所需大小的内存区域。怎么样,是好是坏?

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - C++中的显式代码并行性

c++ - 奇怪的包含依赖

kubernetes - Kubernetes 中命名空间的使用