Difference between revisions of "CPP/Namespaces"

From ProgrammingExamples
< CPP
Jump to: navigation, search
(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…')
 
(Namespaces.cpp)
 
Line 2: Line 2:
 
<source lang="cpp">
 
<source lang="cpp">
 
#include <iostream>
 
#include <iostream>
 +
using namespace std;
  
namespace Namespaces
+
namespace Math{
{
+
bool isOdd(const int n){ return (n & 1) == 1; }
  double add(const double a, const double b)
+
bool isEven(const int n){ return !isOdd(n); }
  {
+
static const float PI = 3.1415f;
  return a + b;
+
static const float DEGTORAD = PI/180.0f;
  }
+
 
}
 
}
 
 
int main(int argc, char *argv[])
+
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;
  
  //cout << add(3.4, 4.2); //does not work - "add was not declared in this scope"
 
 
 
  std::cout << Namespaces::add(3.4, 4.2);
 
 
 
  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;
 
}