Monday, October 18, 2010

Lesson 2: Libraries & Namespaces

The Introduction: Namespaces
In order to use cout, cin, or endl, you must first declare them.
In our Hello World example, they were declared upon use with std::cout<<..
However, you can instead declare each one at the beginning of your script with the following and not have to declare it in middle of your program:
using std::cout;
using std::endl;
using std::cin;

But as most commonly used, the whole standard namespace may be declared with the following:
using namespace std;

Therefore, the same script above could be written as either of the following in addition to the initial way.

The Code: Namespaces
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
cout<<"Hello World!";
cin.get();
return 0;
}

OR

#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World!";
cin.get();
return 0;
}

Libraries & Namespaces
Namespaces are very similar to Libraries: declaring either one enables you to use the functions that lie inside of them. They are not the same, however.

#include <iostream>
Using a library like IOStream will let you use any function within the library; however, if a function or variable within the file conflicts with a function or variable in another library or in your program, your program will not compile.

std::cout<<"..."
With a namespace, on the other hand, you can use any program from the std namespace, but at any time, you could simply choose to use "cout" from a different namespace. Although another "cout" function is unlikely, one might look like this:
dffrnt::cout<<".."
And this version of cout might do something completely different.

No comments:

Post a Comment