【发布时间】:2015-12-17 13:11:49
【问题描述】:
我尝试了以下代码。当我编译时,我得到错误,有 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;
}
编辑 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 Variable using using identifier:"<<first_var<<endl;
// using namespace second_space;
cout<<"Second Namespace Variable using using identifier:"<<first_var<<endl;
}
输出:
Hello World
First Namespace Variable using namespace identifier:0
First Namespace Variable using using identifier:1
Second Namespace Variable using using identifier:1
【问题讨论】:
-
据我所知,没有
stop using namespace的概念...... -
您可以使用完全限定名称。你到底想达到什么目的?这个问题一般在头文件中使用
using namespace指令时会出现,应该避免。 -
我试图了解命名空间的范围,它是否被最新的命名空间覆盖
-
@CVS 不,它没有。但是你可以将你的 using 指令——以及依赖它们的代码——括在大括号中。在右大括号处,这些名称将不再在范围内。
-
@Andrew Sure.. 这就是我们如何让它按照我们想要的方式工作:)
标签: c++ namespaces