未命名的名称空间导致值不正确

时间:2018-11-25 02:57:34

标签: c++

我在带有Visual Studio 2015社区版的Windows 7机器上。

考虑以下代码:

#include "stdafx.h"
#include "iostream"
using namespace std;

namespace 
{
    int y=4;
    int x=6;
}
int u = ::y;
int y = ::y; 
int x = 567;



int main()
{
    cout << u << "\n";
    cout << ::x << "\n";
    //cout << y << "\n";
    cout<< ::y << "\n";
    int y2;

    cin >> y2;
    return 0;
}

该程序的结果是:

4 567 0

如果我们看到u和x是正确的,而y是错误的。为什么?

1 个答案:

答案 0 :(得分:3)

int y = ::y

第二个y与第一个相同-变量使用其自己的值初始化。由于它是一个全局变量,因此它自己的值为零。

一旦声明在全局名称空间中引入了名称y,就没有语法可以从未命名的名称空间访问y。变量声明可从其自己的初始化程序访问。