Namespaces in C++
Namespaces are a C++ feature designed to eliminate name conflicts,
such as having two classes, each in different libraries, called String.
Before namespaces were added to the language, library developers tried to make their names unique by adding letters to them:
One developer's string class might be called GCString, whereas another developer might call it TKString,
the string class in MFC is called CString, and so on.
This approach is ugly and reduces, but doesn't prevent, name conflicts.
With namespaces, classes can have simple names.
Name conflicts are much less likely,
because in addition to a short or local name,
classes have a fully qualified name that includes their namespace.
Here's a slightly artificial example (normally namespaces are used in separate libraries,
not jumbled together in one piece of code like this) that illustrates how they work
:
کد:
namespace One
{
class Common
{
private:
int x;
public:
Common(int a): x(a) {}
int getx() {return x;}
};
void Do()
{
Common c(3);
Console::WriteLine(__box(c.getx()));
}
}
namespace Two
{
class Common
{
private:
double d1, d2;
public:
Common(double param1) : d1(param1),d2(param1) {}
double getd1() {return d1;}
double getd2() {return d2;}
};
void Do()
{
Common c(3);
String* output = String::Concat(__box(c.getd1()), S" " ,
__box(c.getd2()));
Console::WriteLine(output);
}
}
int _tmain()
{
//Common c(3); // ambiguous
One::Common c1(3);
Two::Common c2(3);
//Do(); //ambiguous
One::Do();
Two::Do();
return 0;
}