Brian said:
Why is this necessary? I've been writting cout for every program I've
written and haven't run into any problems. Can you explain why this is
better than just cout?
Namespaces were designed into C++ to fix the problem of name collision. Say
you decided to make a class called string (not neccessarily a good idea, but
just to show my point). Something like this (the #include of <cmath> is
just so it'll compile with the using statement).
#include <cmath>
using namespace std;
class string
{
public:
char data[1000];
};
int main()
{
string MyString;
}
Seems simple enough, and compiles. Now, however, say I want a vector of my
string class. I would attempt to do this:
#include <vector>
using namespace std;
class string
{
public:
char data[1000];
};
int main()
{
vector< string > MyVector;
}
But, it doesn't compile (in VC++ .net 2003 anyway). The error I get is
this:
c:\Source\working\Console2\Console2.cpp(14) : error C2872: 'string' :
ambiguous symbol
could be 'c:\Source\working\Console2\Console2.cpp(6) : string'
or 'c:\Program Files\Microsoft Visual Studio .NET
2003\Vc7\include\xstring(1562) : std::string'
That's a name collision. <vector> also includes <string> somewhere, which
is the std::string. Now the compiler doesn't know which vector< string >
I'm talking about. Is it std::string or my local string which is in the
unnamed namespace? To fix it I would have to:
vector< ::string > MyVector;
saying use the string from the unnamed namespace. But, to get rid of all
this finagelling, just don't import every single thing from the std it finds
and either just import the ones you want to use or prefix them with std::.
Personally, I prefix everything with std::, it's not really that difficult.
Which makes the program become:
#include <vector>
class string
{
public:
char data[1000];
};
int main()
{
std::vector< string > MyVector;
}
Please note, I am not suggesting in the least that you make classes with the
same name as templates/classes in the STL. I just used string cause it was
easiest to show.
Namespaces were designed to avoid name collision. using namespace whatever
totally defeats the purpose.