我在装有 visual studio 2015 community edition 的 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 是错的。为什么?
最佳答案
int y = ::y
此处第二个 y
与第一个相同 - 变量用自己的值初始化。由于它是一个全局变量,它自己的值为零。
一旦声明将名称 y
引入全局命名空间,就没有语法可以从未命名的命名空间访问 y
。变量声明可从其自身的初始化器访问。
关于c++ - 未命名的命名空间导致值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464279/