使用 "::member" 引用全局命名空间有什么用吗?

Is there any use in using "::member" to reference the global namespace?

本文关键字:什么 全局 member 引用 使用 命名空间      更新时间:2023-10-16

在C++中,命名空间myNamespace的成员可以引用为myNamespace::member

但是,显然存在一种类似于上述语法的语法,用于引用全局命名空间 - 简单地::member .考虑:

int foo() {
    return 4;
}
::foo(); // What is the difference between
foo();   // these two lines?

简而言之,在这种情况下使用 foo();::foo(); 之间是否存在功能差异,或者它们是否完全相同?

示例代码:

#include <iostream>
void foo() {
  std::cout << 1;
}
namespace my_ns
{
  void foo() {
    std::cout << 2;
  }
  void goo1() {
    ::foo();
  }
  void goo2() {
    foo();
  }
}
int main(int c, char** args) {
  my_ns::goo1();
  my_ns::goo2();
  return 0;
}