So we want to prevent the usage of
using namespace std; right?
The way to code is then:
std::cout<<"hi"<<std::endl;
std::string theString("I am a string");
std::cout<<theString<<std::endl;
But there are so many keywords and reserved items that typing
std:: becomes tedious. Instead, use one time code like this:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
And now we can use cout, endl and string without typing the scope resultion operator all the time in front of them.
Here is a sample.
Code:
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
namespace falsepride
{
int theInt(5);
string theString("Hello");
}
//From now on, we will use falsepride's variables!
using falsepride::theInt;
using falsepride::theString;
int main()
{
cout<<theInt<<endl;
cout<<theString<<endl;
return 0;
}
There is a small problem now. Now the rest of your collegues aren't allowed to define their stuff with the same names that you used.
The neat way to do is this (and I will add my own little project in my own namespace):
Code:
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
//Each programmer his own workspace!
namespace falsepride
{
int theInt(5);
string theString("Hello");
}
namespace valmont
{
int theInt(12);
string theString("SPQR");
}
int main()
{
//Use falspride's definitions.
cout<<falsepride::theInt<<endl;
cout<<falsepride::theString<<endl;
//Use valmont's definitions.
cout<<valmont::theInt<<endl;
cout<<valmont::theString<<endl;
return 0;
}
A last example. We both are going to define a simple output function. But there will also be a global version. Just read the comments in the code for details.
Code:
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
//The global version. This one is slightly safer and certainly
//faster for LOTS of shifting with HUGE amounts of text.
void print_the_stuff(const string& stuff)
{
cout<<stuff<<endl;
}
//falsepride chooses the unsafe yet modern way.
namespace falsepride
{
void print_the_stuff(string stuff)
{
cout<<stuff<<endl;
}
}
//Val does it the unsafe and old fashioned way.
namespace valmont
{
void print_the_stuff(char* stuff)
{
cout<<stuff<<endl;
}
}
int main()
{
//Use falspride's version.
falsepride::print_the_stuff("This is from falsepride.");
//Use valmont's version.
valmont::print_the_stuff("This is from Valmont.");
//Use global version.
print_the_stuff("Global version here!");
return 0;
}
Play with it. For more questions, just ask.