Why “using namespace X;” is not allowed inside class/struct level?

后端 未结 5 669
走了就别回头了
走了就别回头了 2020-11-27 15:35
class C {
  using namespace std;  // error
};
namespace N {
  using namespace std; // ok
}
int main () {
  using namespace std; // ok
}

Edi

5条回答
  •  伪装坚强ぢ
    2020-11-27 15:56

    This is probably disallowed because of openness vs closedness.

    • Classes and structs in C++ are always closed entities. They are defined in exactly one place (although you can split declaration and implementation).
    • namespaces can be opened, re-opened and extended arbitrarily often.

    Importing namespaces into classes would lead to funny cases like this:

    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.
    }
    

提交回复
热议问题