小编CVS*_*CVS的帖子

使用名称范围

我尝试了下面这段代码.当我编译时,我得到错误,那里有first_var的模糊实例,而我在最后一个cout之前引入了使用命名空间second_space

我想这是因为最后一个cout使用两个名称空间.命名空间没有覆盖概念?无论如何,命名空间范围可以结束,还是从使用命名空间点继续到文件末尾?

#include<iostream.h>
namespace first_space{
    int first_var;
}
namespace second_space{
    int first_var = 1;
}
int main()
{
    cout<<"Hello World"<<endl;
    cout<<"First Namespace Variable using namespace identifier:"<<first_space::first_var<<endl;
    using namespace first_space;
    cout<<"First Namespace Variable using using identifier:"<<first_var<<endl;
    using namespace second_space;
    cout<<"Second Namespace Variable using using identifier:"<<first_var<<endl;
}
Run Code Online (Sandbox Code Playgroud)

编辑1:

我在下面尝试过类似的东西.声明在main中具有相同名称的变量,为其分配值1,然后使用下面的命名空间使用.但是我看到,first_var的值在最后两个cout中打印为1.这里没有歧义.那么命名空间没有任何影响?为什么会这样?

#include<iostream.h>
namespace first_space{
    int first_var;
}
namespace second_space{
    int first_var = 1;
}
int main()
{
    int first_var =1 ;
    using namespace first_space;
    cout<<"Hello World"<<endl;
    cout<<"First Namespace Variable using namespace identifier:"<<first_space::first_var<<endl;
    cout<<"First Namespace …
Run Code Online (Sandbox Code Playgroud)

c++ namespaces

3
推荐指数
1
解决办法
199
查看次数

标签 统计

c++ ×1

namespaces ×1