没有命名空间的"namespace::fn"和"::fn"有什么区别?

What is the difference between "namespace::fn" and "::fn" without the namespace?

本文关键字:fn 什么 区别 namespace 命名空间      更新时间:2023-10-16

可能重复:
C++命名空间问题

我看到了几个没有名称空间的例子。这样做有什么好处?

::fn指的是全局命名空间中名为fn的东西。

::fn引用全局命名空间中的某个内容(它是一个绝对路径(。注意,您可以使用using <obj>;using namespace <name>将内容导入全局命名空间;

namespace::fn指的是相对于当前命名空间的命名空间中的某些内容(它是一个相对路径(。

namespace X
{
     namespace Y
     {
           int Z()
           {
               N::fn();
               // Compiler looks for
               //      ::X::Y::N::fn()
               //      ::X::N::fn()
               //      ::N::fn()
               //
               // The search is done in that order the first found
               // is used. Note this is done at compile time only.

               ::fn(); // Absolute path. No search done.
                       // looks for `fn()` in the global namespace
               fn();   // Relative path no namespace
                       // Searchs for ::X::Y::fn()
                       //             ::X::fn()
                       //             ::fn()

               ::X::fn(); // Absolute path no search done.
                          // looks for `fn()` in the namespace X which must be
                          // in the global namespace.
           }
     }          
 }

当您有两个具有此名称的变量时,您希望使用::fn,一个在函数内声明,另一个在全局范围内声明。因此,如果你想在该函数中处理全局fn(声明本地fn的地方(,你需要调用它::fn来区分它们

int fn = 5;
int main (int argc, char *argv[])
{
      int fn = 10;
      std::cout << "local fn is " << fn << " global fn is " << ::fn;  
      return 0;
}