Home > Mobile >  namespace question in c how to use "using namespace"
namespace question in c how to use "using namespace"

Time:09-30

I have a very basic question about namespace

when should I use "using namespace A::B"?

I know I shouldn't use it in header files, how about .cpp file? In my test.cpp:

namespace A{
namespace B{
namespace C{
      A::B::Object obj = ....
}
}
}

the full namespace is A::B::Object as I have right now, Do I actually need A::B? Can I just have Object obj = ....? Should I use using namespace A::B and then have Object obj = ....? I am not sure what this actually means:

    namespace A{
    namespace B{
    namespace C{
          .....
    }
    }
    }

I know This means all the contents inside it will have namespace A::B::C, but does it also mean:

using namespace A
using namespace A::B
using namespace A::B::C

implicitly for the contents inside it?

CodePudding user response:

Because obj is not on the root (global) namespace if you write outside its namespace Object the identifier will be not found. So you have a few options:

  • use fully qualified name:

    A::B::C::Object obj = ...
    
  • use using declaration:

    using namespace A::B::C;
    Object obj = ...;
    
  • use using declaration:

    using A::B::C::Object
    Object obj = ...
    
  • use namespace alias:

    namespace X = A::B::C;
    X::Object obj = ...
    

And basically any combination of above e.g.:

namespace Y = A::B;
Y::C Object obj = ...

using namespace A::B;
C::Object obj = ...

CodePudding user response:

Statements placed in the inner namespaces will be able to reference classes, typedefs, functions, etc from the outer namespaces without explicitly typing them.

namespace A {
    class AClass { };
    namespace B {
        class BClass {
            AClass a;   // Does not require A::AClass
        };
    }
}

In addition to using namespace, another way to shorten lengthy compounded namespaces in a .cpp file is to declare a new, shorter namespace:

// MyClass.h
namespace A {
    namespace B {
        class MyClass { 
        public:
            void f();               
        };
    }
}
// MyClass.cpp
#include "MyClass.h"

namespace AB = ::A::B;

void AB::MyClass::f() {
    // impl...
}

(Note that the optional :: at the start of ::A::B explictly tells the compiler that ::A::B is the full path, which is potentially useful if a header had an SomeOtherSpace::A::B namespace and carelessly wrote using namespace SomeOtherSpace.)

  •  Tags:  
  • c
  • Related