【问题标题】:Using namespace scope使用命名空间范围
【发布时间】: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


【解决方案1】:

是的,你是对的,在第二个 using 语句之后,变量 first_var 现在是模棱两可的,因为就 name lookup 而言,这两个命名空间都是有效的并且具有相同的优先级。

两种解决方法是

a) 添加大括号以强制执行匿名范围 (live demo)

{
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;
}

b) 删除 using 关键字并直接使用命名空间范围

cout << "First Namespace Variable using using identifier:" << first_space::first_var << endl;
cout << "Second Namespace Variable using using identifier:" << second_space::first_var << endl;

我个人会选择选项 b。首先添加命名空间的主要原因之一是避免歧义问题,因此用一堆 using 语句污染当前范围会破坏这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多