我看到了这两个短语的用法:全局范围和全局名称空间。它们之间有什么区别?
在 C++ 中,每个名称都有其作用域,超出该作用域就不存在。范围可以通过多种方式定义:它可以通过以下方式定义名称空间, 功能, classes并且只是{ }.
因此,全局或其他命名空间定义了一个范围。全局命名空间指的是使用::
,并且在此命名空间中定义的符号被认为具有全局范围。默认情况下,符号存在于全局命名空间中,除非它是在以关键字开头的块内定义的namespace
,或者它是类的成员,或者函数的局部变量:
int a; //this a is defined in global namespace
//which means, its scope is global. It exists everywhere.
namespace N
{
int a; //it is defined in a non-global namespace called `N`
//outside N it doesn't exist.
}
void f()
{
int a; //its scope is the function itself.
//outside the function, a doesn't exist.
{
int a; //the curly braces defines this a's scope!
}
}
class A
{
int a; //its scope is the class itself.
//outside A, it doesn't exist.
};
另请注意,name可以被命名空间、函数或类定义的内部作用域隐藏。所以这个名字a
命名空间内N
隐藏名字a
在全局命名空间中。同样,函数和类中的名称隐藏了全局命名空间中的名称。如果你遇到这样的情况,那么你可以使用::a
引用全局命名空间中定义的名称:
int a = 10;
namespace N
{
int a = 100;
void f()
{
int a = 1000;
std::cout << a << std::endl; //prints 1000
std::cout << N::a << std::endl; //prints 100
std::cout << ::a << std::endl; //prints 10
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)