没有命名空间的"namespace::fn"和"::fn"有什么区别?
What is the difference between "namespace::fn" and "::fn" without the namespace?
可能重复:
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;
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "double* grade"、"double *grade"和"double* fn()"有什么区别?
- v8 源代码中 ArrayMap 函数的回调 fn 参数是什么?
- 没有命名空间的"namespace::fn"和"::fn"有什么区别?