在C++中"使用namespace :: X"中的leading :: mean是什么意思?

Dud*_*ero 16 c++ namespaces using

可以有人解释我以下命名空间用法之间的区别:

using namespace ::layer::module;

using namespace layer::module;

是什么原因导致了额外的::layer

CB *_*ley 24

如果在以下环境中使用它会有所不同:

namespace layer {
    namespace module {
        int x;
    }
}

namespace nest {
    namespace layer {
        namespace module {
            int x;
        }
    }
    using namespace /*::*/layer::module;
}
Run Code Online (Sandbox Code Playgroud)

初始化后::,第一个x将在using指令后可见,没有它,第二个x内部nest::layer::module将变得可见.


spr*_*aff 14

第二种情况可能是X::layer::module在那里using namespace X已经发生了.

在第一种情况下,前缀::意味着"编译器,不要聪明,从全局命名空间开始".


sbi*_*sbi 13

前导::是指全局命名空间.以a开头的任何限定标识符::将始终引用全局命名空间中的某个标识符.不同之处在于,您在全局和某些本地命名空间中拥有相同的内容:

namespace layer { namespace module {
    void f();
} }

namespace blah { 
  namespace layer { namespace module {
      void f();
  } }

  using namespace layer::module // note: no leading ::
                                // refers to local namespace layer
  void g() {
    f(); // calls blah::layer::module::f();
  }
}

namespace blubb {
  namespace layer { namespace module {
      void f();
  } }

  using namespace ::layer::module // note: leading ::
                                  // refers to global namespace layer
  void g() {
    f(); // calls ::layer::module::f();
  }
}
Run Code Online (Sandbox Code Playgroud)


Alo*_*ave 5

它在 C++ 中称为限定名称查找

这意味着被引用的层命名空间是全局命名空间之外的命名空间,而不是另一个名为 layer 的嵌套命名空间。

Standerdese 粉丝:
$3.4.3/1

“类或名称空间成员的名称可以在 :: 范围解析运算符 (5.1) 之后引用,该运算符应用于指定其类或名称空间的嵌套名称说明符。在查找 :: 范围解析之前的名称期间运算符、对象、函数和枚举器名称将被忽略。如果找到的名称不是类名(第 9 条)或命名空间名(7.3.1),则程序格式错误。”