c++,使用了命名空间,那么我下面的程序当中可不可以设定和命名空间同样的变量名字??

2025-04-13 20:55:20
推荐回答(1个)
回答1:

在相同的作用域,不行,如:
#include "stdafx.h"
#include
//#pragma warning(disable:4996)
using namespace std;
int std = 10; //命名冲突

//这是VS 主函数声明,如果有问题,将上句改成:
//int main()
int _tmain(int argc, _TCHAR* argv[])
{
cout << std << endl;
//如果下句出现问题,请添加头文件引用:#include
system("pause"); //防止窗口一闪而退
return 0;
}

再看看这个:
#include "stdafx.h"
#include
//#pragma warning(disable:4996)
using namespace std;
//这是VS 主函数声明,如果有问题,将上句改成:
//int main()
int _tmain(int argc, _TCHAR* argv[])
{
int std = 10; //可以,和 using namespace std; 不是在同一个作用域
cout << std << endl; //访问局部变量 std
::std::cout << "这里的 std 是全局的,即 using namespace std; 中的 std。" << endl;
//如果下句出现问题,请添加头文件引用:#include
system("pause"); //防止窗口一闪而退
return 0;
}