【问题标题】:What does a leading :: mean in "using namespace ::X" in C++在 C++ 中的“使用命名空间 ::X”中,前导 :: 是什么意思
【发布时间】:2011-10-11 00:44:12
【问题描述】:

谁能解释一下以下命名空间用法之间的区别:

using namespace ::layer::module;

using namespace layer::module;

是什么导致::layer 之前出现额外的layer

【问题讨论】:

  • @Tom:但这真的是个骗局吗?
  • @sbi: 是的,'前面的 :: 是什么意思 - 为什么使用它?但由于这里的答案比那里的多,我不会关闭 - 我只是认为该链接会有所帮助

标签: c++ namespaces using


【解决方案1】:

如果在以下上下文中使用会有所不同:

namespace layer {
    namespace module {
        int x;
    }
}

namespace nest {
    namespace layer {
        namespace module {
            int x;
        }
    }
    using namespace /*::*/layer::module;
}

使用初始 ::,第一个 x 在 using 指令之后可见,没有它,nest::layer::module 内的第二个 x 将可见。

【讨论】:

    【解决方案2】:

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

    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();
      }
    }
    

    【讨论】:

      【解决方案3】:

      第二种情况可能是X::layer::module,其中using namespace X 已经发生。

      在第一种情况下,前缀:: 的意思是“编译器,别聪明,从全局命名空间开始”。

      【讨论】:

        【解决方案4】:

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

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

        对于 Standerdese 的粉丝:
        $3.4.3/1

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-21
          • 1970-01-01
          • 2013-09-29
          • 2012-01-21
          • 1970-01-01
          • 2016-01-27
          相关资源
          最近更新 更多