Global scope vs global namespace(全局作用域与全局命名空间)
问题描述
我看到了这两个短语的用法:全局作用域和全局命名空间.它们有什么区别?
I saw usages of these two phrases: global scope and global namespace. What is the difference between them?
推荐答案
在 C++ 中,每个名称都有其不存在的范围.作用域可以通过多种方式定义:它可以由命名空间、函数、类和仅{}.
In C++, every name has its scope outside which it doesn't exist. A scope can be defined by many ways : it can be defined by namespace, functions, classes and just { }.
所以一个命名空间,无论是全局的还是其他的,定义了一个范围.全局命名空间是指使用::
,在这个命名空间中定义的符号被称为具有全局作用域.默认情况下,符号存在于全局命名空间中,除非它定义在以关键字 namespace
开头的块中,或者它是类的成员,或者函数的局部变量:>
So a namespace, global or otherwise, defines a scope. The global namespace refers to using ::
, and the symbols defined in this namespace are said to have global scope. A symbol, by default, exists in a global namespace, unless it is defined inside a block starts with keyword namespace
, or it is a member of a class, or a local variable of a function:
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 可以被命名空间、函数或类定义的内部作用域隐藏.因此,名称空间 N
中的名称 a
在全局命名空间中隐藏了名称 a
.同样,函数和类中的名称隐藏了全局命名空间中的名称.如果你遇到这种情况,那么你可以使用::a
来引用全局命名空间中定义的名字:
Also note that a name can be hidden by inner scope defined by either namespace, function, or class. So the name a
inside namespace N
hides the name a
in the global namspace. In the same way, the name in the function and class hides the name in the global namespace. If you face such situation, then you can use ::a
to refer to the name defined in the global namespace:
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
}
}
这篇关于全局作用域与全局命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:全局作用域与全局命名空间
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01