» Namespaces by Travis Dane |
|
(Login to remove green text ads)
Last tutorial i spoke about Function Overloading, That it was a method to seperate two functions with the same name, However,
There's another way to do this and it allows you to keep the same argument types as well, Namespaces.
Basically Namespaces are nothing more than putting something before the function to differ it from another like so:
Code:
#include <iostream> // Include the newest input-output stream header
#include <conio.h>
void aPrint(void) // A function called "Print", We label it with an "a" to distiguise it from other "Print" Functions
{
cout << "Hello!" << endl;
}
void bPrint(void) // Another "Print" function
{
cout << "Hello!" << endl;
}
int main(void) // The program entry point
{
aPrint(); // Call the first function
bPrint(); // Call the second function
getch(); // Prevent the program from exiting premature
return 0; // return succes
}
But this looks ugly and can be done automaticelly and more structured by means of a Namespace like so:
Code:
#include <iostream> // Include the newest input-output stream header
#include <conio.h>
namespace a // The namespace a
{
void Print(void); // Our first function
}
void a::Print(void) /* Here we define the function, Notice the "a::" before it, We do this to tell the compiler that
we mean the function that belongs to the namespace a
*/
{
cout << "Hello!" << endl;
}
namespace b // The namespace b
{
void Print(void); // Our second function
}
void b::Print(void) /* Here we define the function, Notice the "b::" before it, We do this to tell the compiler that
we mean the function that belongs to the namespace b
*/
{
cout << "Hello!" << endl;
}
int main(void) // The program entry point
{
// Now to call the different print functions
a::Print();
b::Print();
getch(); // Prevent the program from exiting premature
return 0; // return succes
}
Remember, I might have only used functions in this tutorial but variables like integers, float or whatever can all be
used in a namespace.
Sometimes you'll use a single namespace alot of times, To avoid having to use the "::" all the time you can use:
Code:
using namespace yournamespace;
By doing this it will automaticelly search through the namespace for a called function without you have to specify it with
a "::" .
That's it! Easy huh?
Some compilers, Like VC++, Will have a nifty feature that will automaticelly show all the contents of in this case a
namespace as soon as you specify it like so:
In VC++ this feature is called "Intellisense".
Now be aware that VC++ 6 and lower have certain problems with namespaces like: Functions won't show
up in intellisense if they haven't been defined yet, Everything the namespace contains will be put in the "globals" category
of the variables, Sucky huh? This all has been fixed in VC++ .NET so start saving.
If you experience any problems with the tutorials or have questions, Feel free to ask them.
|
|