Namespaces
By default, we use the std
namespace. It allows us to use, e.g., the cout
statement. If we didn't write using namespace std;
at the beginning, we would have to write std::
before every object from this namespace. We can create our namespaces and refer to their objects the same way. Using namespaces allows us to avoid variable name conflicts (an a
variable from the x
namespace isn't equal to an a
variable from the y
namespace, so we can safely repeat the variable names in different namespaces). We can also use the using namespace
directive for our namespaces.
The MyNewLine
class in the example below will redefine the endl
manipulator in the MySpace
namespace (it will make a few enters).
#include <iostream>
int x = 5;
namespace A {
int y = 20;
}
namespace B {
int y = 30;
}
using namespace A;
namespace MySpace {
using namespace std;
class MyNewLine {
string sign;
public:
MyNewLine(string sign = "\n\n\n"){this -> sign = sign;};
string rSign() {
return sign;
}
};
ostream & operator<<(ostream &out, MyNewLine &obj) { // ostream - output stream
return out << obj.rSign();
}
MyNewLine endl;
}
using namespace MySpace;
int main() {
int x = 10;
std::cout << x << std::endl;
std::cout << ::x << std::endl;
std::cout << A::y << std::endl;
std::cout << B::y << std::endl;
std::cout << y << std::endl;
std::cout << std::endl;
MyNewLine variable("abcdefgh");
std::cout << variable << MySpace::endl;
return 0;
}