/* Author: Arun Somasundaram, CSE Dept, OSU Simple program for namespaces. A namespace is a mechanism for logical grouping. A namespace is a scope. */ #include using namespace std; namespace MathDataFunctions{ float PI = 3.142; //Some Trivial Math Operations float add(float a, float b); float subtract(float a, float b); float addSubtract(float a, float b, float c); // a + b - c class ComplexNumber{ private: float re, im; public: ComplexNumber(float r, float i){ re = r; im = i; cout << "Complex Number ( " << re << ", " << im << " )" << endl;} }; } float MathDataFunctions::add(float a, float b){ return a + b; } float MathDataFunctions::subtract(float a, float b){ return a - b; } float MathDataFunctions::addSubtract(float a, float b, float c){ float d = add(a, b); //You don't need MathDataFunctions::add(a, b); return (d - c); } // A namespace is open. You can add names to it from several namespace declarations. namespace MathDataFunctions{ //Add multiply function to existing namespace float multiply(float a, float b){return a*b;} } namespace ClashWithMathDataFunctions{ float subtract(float a, float b){return (b-a);} } int main(){ cout << "Value of PI is " << MathDataFunctions::PI << endl; typedef MathDataFunctions::ComplexNumber MathComplex; MathComplex cNum1(10, 20); cout << MathDataFunctions::add(2, 3) << endl; cout << MathDataFunctions::subtract(2, 3) << endl; MathDataFunctions::ComplexNumber cNum2(100, 200); using MathDataFunctions::add; //using declaration cout << add(2, 3) << endl; //cout << subtract(2, 3) << endl; //Error why? using namespace MathDataFunctions; cout << add(2, 3) << endl; //After the using directive cout << subtract(2, 3) << endl; //After the using directive cout << multiply(2, 3) << endl; //After the using directive using ClashWithMathDataFunctions::subtract; cout << subtract(2, 3) << endl; //After the using declaration return 0; }