":: "在变量名 C++ 之前
问题描述:
#include <iostream>
using namespace std;
int d = 10;
int main()
{
int d = 20;
{
int d = 30;
cout << d << endl << ::d; // what does it mean?
}
return 0;
}
输出为:
30
10
我不明白为什么 "::d
" 给出 10?有人可以给我解释一下吗?
I don't understand why "::d
" gives 10? Can someone explain it to me please?
答
::d
表示来自全局命名空间的 d
::d
means d
from global namespace
三个不同的变量具有相似的名称d
.一个在全局命名空间d=10
中,一个在main
函数的作用域内(20
),最后一个在主函数(30
).
There are three different variables with similar name d
. One is in global namespace d=10
, one is inside scope of main
function (20
), and the last one is inside internal block of the main function (30
).
在每个块中,您可以(通过名称)访问相应的变量并且始终可以访问全局命名空间(通过::
).
Inside every block you have access (by name) to corresponding variable and always have access to the global namespace (by ::
).