为什么是“使用命名空间 X;”不允许在类/结构级别?

新手上路,请多包涵
class C {
  using namespace std;  // error
};
namespace N {
  using namespace std; // ok
}
int main () {
  using namespace std; // ok
}

我想知道它背后的动机。

原文由 iammilind 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 861
2 个回答

我不确切知道,但我的猜测是在类范围内允许这样做可能会导致混淆:

 namespace Hello
{
    typedef int World;
}

class Blah
{
    using namespace Hello;
public:
    World DoSomething();
}

//Should this be just World or Hello::World ?
World Blah::DoSomething()
{
    //Is the using namespace valid in here?
}

由于没有明显的方法可以做到这一点,标准只是说你不能。

现在,当我们谈论命名空间范围时,这不那么令人困惑的原因:

 namespace Hello
{
    typedef int World;
}

namespace Other
{
    using namespace Hello;
    World DoSomething();
}

//We are outside of any namespace, so we have to fully qualify everything. Therefore either of these are correct:

//Hello was imported into Other, so everything that was in Hello is also in Other. Therefore this is okay:
Other::World Other::DoSomething()
{
    //We're outside of a namespace; obviously the using namespace doesn't apply here.
    //EDIT: Apparently I was wrong about that... see comments.
}

//The original type was Hello::World, so this is okay too.
Hello::World Other::DoSomething()
{
    //Ditto
}

namespace Other
{
    //namespace Hello has been imported into Other, and we are inside Other, so therefore we never need to qualify anything from Hello.
    //Therefore this is unambiguiously right
    World DoSomething()
    {
        //We're inside the namespace, obviously the using namespace does apply here.
    }
}

原文由 Billy ONeal 发布,翻译遵循 CC BY-SA 3.0 许可协议

由于 开放性封闭性,这可能是不允许的。

  • C++ 中的类和结构总是封闭的实体。它们仅在一个地方定义(尽管您可以拆分声明和实现)。
  • 命名空间可以经常任意打开、重新打开和扩展。

将命名空间导入类会导致类似这样的有趣案例:

 namespace Foo {}

struct Bar { using namespace Foo; };

namespace Foo {
using Baz = int; // I've just extended `Bar` with a type alias!
void baz(); // I've just extended `Bar` with what looks like a static function!
// etc.
}

原文由 Daniel Steck 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题