I notice that C++'s std
namespace is spread across several files (like in vector
, string
, iostream
, etc.). How can I accomplish the same thing in my programs? Do I simply declare the same namespace in each individual header file, so that it's something like:
a.h
namespace something
{
class A {};
}
b.h
#include "a.h"
namespace something
{
class B : public A {};
}
And then in, say, main.cpp
, I would just include "b.h" and "a.h" and then using namespace something;
to use the two classes?
You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.
Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. Multiple namespace blocks with the same name are allowed.
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification.
Importing a namespace The basic syntax of a namespace import declaration is as follows: using namespace nmspace_name; After such declaration, all names that we would otherwise have referred as nmspace_name::identifier can be used simply as identifier.
Yes, that is exactly how to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With