Creating a Namespace with a class
To place some program in a namespace, simply include the entire program in
the namespace grouping:
#ifndef CLASSNAME_H
#define CLASSNAME_H
#include<iostream>
#include<ALL OTHERS>
namespace classname
{
class myclass
{
...
...
};
} // end classname
#endif
To make the class defined in this namespace available to your programs, use using directive:
using namespace classname;
To illustrate this let's apply it to the class ID that we used in part 2.
#define ID_H
#ifndef ID_H
#include<iostream>
namespace idclass1
class ID
{
public:
ID( );
ID(int, int, int);
void display();
private:
int left;
int middle;
int right;
};
} // end of idclass namespace
#endif
Now we can use this in a program.
// File ID.h
#ifndef ID_H
#define ID_H
#include<iostream.h>
namespace idclass1
{
class ID
{
public:
ID( );
ID(int, int, int);
void display();
private:
int left;
int middle;
int right;
};
} // end of idclass1 namespace
#endif
// File ID.cpp
#include<iostream.h>
#include "ID.h"
using namespace idclass1;
ID::ID( )
{
// use default values
}
ID::ID(int l, int m, int r)
{
left = l;
middle = m;
right = r;
}
void ID::display()
{
cout << left
<< "-" << middle << "-" << right << endl;
}
// File main_prog.cpp
// This program is a driver written to demonstrate how we can use
// namespaces
#include<iostream>
#include "ID.h"
using namespace std;
// This part will go to the main program, main_prog.cpp
int main( )
{
using namespace idclass1;
ID id1;
id1 = ID(111, 22, 4444);
id1.display( );
return 0;
}
Exercise 9.3
Write the above three program segments in their corresponding
files. Once all files are separated, compile using:
% g++ main_prog.cpp ID.cpp
This will create an a.out file that you can run to display the result, which is 111-22-4444.
Define a new namespace that includes the loan class. Then, create a
program that is similar to ex91.cpp but works with the two namespaces that
you have defined here.