":: "在变量名 C++ 之前 [英] " :: " before a variable name c++

查看:57
本文介绍了":: "在变量名 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 ::).

这篇关于&quot;:: &quot;在变量名 C++ 之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆