If you are going to make a new namespace don’t you have to use a class files in order to do so? |
No, not at all. One can have ordinary variables, functions, POD structs - whatever you like in a namespace. The only requirement is to refer to them correctly, either with the scope operator, a namespace alias, or a using declaration for a type. Namespaces can be nested as well.
This example is rather contrived, but it shows how a namespace can be used to store constants, as one sort of usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
namespace PhysicsConstants {
const double Avogadro = 6.02214085774e23;
struct MyConstants {
const double a = 1.00023;
const auto b = 2.0456;
};
} // end of PhysicsConstants
.
.
.
namespace PhyC = PhysicsConstants; // namespace alias
std::cout << "Avogadro const is " << PhyC::Avogadro << "\n";
// without alias
std::cout << "Avogadro const is " << PhysicsConstants::Avogadro << "\n";
// using declaration for a type
using mc = PhysicsConstants::MyConstants;
std::cout << "My a is " << mc::a << "\n";
|
One doesn't have to put everything into one namespace declaration, I could have done
MyConstants
like this:
1 2 3 4 5 6 7 8
|
namespace PhysicsConstants {
struct MyConstants {
const double a = 1.00023;
const auto b {2.0456}; // use auto and brace init rather than double C++11
};
} // end of PhysicsConstants ns
|
Note that using an entire namespace is a bad idea - especially
using namespace std;
read up about that on Google.
using
one thing out of a ns is OK, like
using std::cout;
, but that becomes tiresome as well, so just use
std::cout
or
std::find
or
mc::a
or whatever it is.
God Luck !!