Datasheet
The implementation of a method or function can also be handled in a namespace:
// namespaces.cpp
#include <iostream>
#include “namespaces.h”
namespace mycode {
void foo() {
std::cout << “foo() called in the mycode namespace” << std::endl;
}
}
By placing your version of foo() in the namespace “mycode,” it is isolated from the foo() function
provided by the third-party library. To call the namespace-enabled version of
foo(), prepend the
namespace onto the function name as follows.
mycode::foo(); // Calls the “foo” function in the “mycode” namespace
Any code that falls within a “mycode” namespace block can call other code within the same namespace
without explicitly prepending the namespace. This implicit namespace is useful in making the code
more precise and readable. You can also avoid prepending of namespaces with the
using directive. This
directive tells the compiler that the subsequent code is making use of names in the specified namespace.
The namespace is thus implied for the code that follows:
// usingnamespaces.cpp
#include “namespaces.h”
using namespace mycode;
int main(int argc, char** argv)
{
foo(); // Implies mycode::foo();
}
A single source file can contain multiple using directives, but beware of overusing this shortcut. In the
extreme case, if you declare that you’re using every namespace known to humanity, you’re effectively
eliminating namespaces entirely! Name conflicts will again result if you are using two namespaces that
contain the same names. It is also important to know in which namespace your code is operating so that
you don’t end up accidentally calling the wrong version of a function.
You’ve seen the namespace syntax before — we used it in the Hello, World program.
cout and endl are
actually names defined in the
std namespace. We could have rewritten Hello, World with the using
directive as shown here:
5
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 5