Difference between revisions of "CPP/Namespaces"
From ProgrammingExamples
< CPP
Daviddoria (Talk | contribs) (Created page with '==Namespaces.cpp== <source lang="cpp"> #include <iostream> namespace Namespaces { double add(const double a, const double b) { return a + b; } } int main(int argc, c…') |
FirstPerson (Talk | contribs) (→Namespaces.cpp) |
||
Line 2: | Line 2: | ||
<source lang="cpp"> | <source lang="cpp"> | ||
#include <iostream> | #include <iostream> | ||
+ | using namespace std; | ||
− | namespace | + | namespace Math{ |
− | { | + | bool isOdd(const int n){ return (n & 1) == 1; } |
− | + | bool isEven(const int n){ return !isOdd(n); } | |
− | + | static const float PI = 3.1415f; | |
− | + | static const float DEGTORAD = PI/180.0f; | |
− | + | ||
} | } | ||
− | int main( | + | int main(){ |
− | { | + | //use the scope operator, :: , to access a function or variable; |
+ | for(int i = 1; i != 10; ++i){ | ||
+ | if( Math::isOdd(i) ){ | ||
+ | cout << i << " is odd " << endl; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | //use the using declaration | ||
+ | { | ||
+ | using Math::isEven; //isEven is only in scope after this semicolon | ||
+ | if( isEven(1010112) ) cout << "\nIts even...\n"; | ||
+ | } //and is invalid after this closing brackets | ||
+ | |||
+ | { | ||
+ | //use everthing from the Math namespace | ||
+ | using namespace Math; | ||
+ | cout << PI << endl; | ||
+ | } | ||
+ | |||
+ | return 0; | ||
− | |||
− | |||
− | |||
− | |||
− | |||
} | } | ||
</source> | </source> |
Latest revision as of 00:27, 29 June 2010
Namespaces.cpp
#include <iostream> using namespace std; namespace Math{ bool isOdd(const int n){ return (n & 1) == 1; } bool isEven(const int n){ return !isOdd(n); } static const float PI = 3.1415f; static const float DEGTORAD = PI/180.0f; } int main(){ //use the scope operator, :: , to access a function or variable; for(int i = 1; i != 10; ++i){ if( Math::isOdd(i) ){ cout << i << " is odd " << endl; } } //use the using declaration { using Math::isEven; //isEven is only in scope after this semicolon if( isEven(1010112) ) cout << "\nIts even...\n"; } //and is invalid after this closing brackets { //use everthing from the Math namespace using namespace Math; cout << PI << endl; } return 0; }