C++/std
Expert: vijayan - 5/14/2009
QuestionHi
i have a question about using std in c++ programming,for instance using 'std::cout' , 'std::cin' or 'std::endl'
could you plz give me a definition for std and tell me the function of std in using of it in code?
Thanx
Bita
AnswerIf the only programs that were ever written were only by one person, things like namespaces probably wouldn't be necessary. However, many programs out there are long, developed by different teams of developers, and use libraries wriiten by some one else. This means that sooner or later someone is going to use the same name for a different purpose and thereby create a name clash. namespaces are a way to decrease/sidestep that possibility.
namespaces are like directories in a file system. All of the standard library is in one directory (called std), and the only way to get to the stuff in that directory is to tell the compiler where to find it. You do that by prefixing the name with std::
#include <iostream>
int main()
{
std::cout << "Hello, world!\n" ;
}
std::cout is basically like saying "Hey compiler! Look in directory std and get me cout!". If you don't tell the compiler where to look, it won't find what you want.
That's why this gives you a nasty little error, the compiler is complaining that it can't find cout:
#include <iostream>
int main()
{
cout << "Hello, world!\n" ;
}
It's somewhat tedious to keep typing std:: in front of everything, so you can also tell the compiler "Assume that I mean std::cout whenever I just say cout." via a using declaration.
#include <iostream>
int main()
{
using std::cout ;
cout << "Hello, world!\n" ;
}
The using std::cout part tells the compiler: wherever you say just cout, you really mean std::cout.
Even that can get tedious, and maybe you want to say "Hey compiler! Look into std:: for everything that is not prefixed with std::". You can do that with a using directive:
#include <iostream>
int main()
{
using namespace std ;
cout << "Hello, world!\n" ;
}
for more information, see:
http://www.cprogramming.com/tutorial/namespaces.html
http://www.icce.rug.nl/docs/cplusplus/cplusplus03.html#Namespaces