Namespaces – avoiding naming conflicts
-
Upload
guy-clements -
Category
Documents
-
view
22 -
download
0
description
Transcript of Namespaces – avoiding naming conflicts
Fall 2004 CS-183Dr. Mark L. Hornick
1
Namespaces – avoiding naming conflicts
What can you do when you have Two classes with the same name? Two functions with identical overloads? Two global objects with the same name?
A real problem All declarations of functions and classes you have
written so far are global
Fall 2004 CS-183Dr. Mark L. Hornick
2
Creating Namespaces
Syntax namespace NAME {…}
Notes: NAME is often elaborate/unique to avoid conflicts We say the items within the { } belong to the
namespace
Fall 2004 CS-183Dr. Mark L. Hornick
3
Namespace Searching
Default Compiler searches current namespace that has
been defined (if there is one) Then global namespace (i.e. ::)
We can force other namespaces to be searched using namespace std; Everything in std is brought into the current (e.g.
global) namespace
Fall 2004 CS-183Dr. Mark L. Hornick
4
Limiting the Default Search
using namespace std; // common Suppose you only want to use cout…
Single definitions can be addedusing std::cout; Only cout will be added The rest of std will not
Fall 2004 CS-183Dr. Mark L. Hornick
5
Nesting – namespaces can contain namespaces
namespace abc {
namespace def {
const int z = 3;
}
}
namespace ghi {
const float z = 7.5;
}
Both namespaces contain a variable named z
Fall 2004 CS-183Dr. Mark L. Hornick
6
Using Nested Namespaces Without shortcuts
int y = abc::def::z;float w = ghi::z;
To favor the int over the floatusing namespace abc::def;int y = z;float w = ghi::z;
orusing abc::def::z; // use only “z” from abc::defint y = z; float w = ghi::z;