C++ Programming Blog

 
 
 
 #include<iostream.h>
 #include<conio.h>

 const int max=20;


 //------------------------------  stack  --------------------------------//


 template <class T>

 class stack
    {
       private:
        T stk[max];

        int top;

       public:
        stack()  { top=-1; }
        void push(T);
        T pop();
    };


 //---------------------------  complex  ---------------------------------//


 class complex
    {
       private:
        float real_part;
        float imaginary_part;

       public:
        complex()  { real_part=0.0;  imaginary_part=0.0; }
        complex(float r,float i)  { real_part=r; imaginary_part=i; }
        friend ostream &operator<<(ostream &o,complex &c);
    };




 //---------------------------   push(T)  --------------------------------//


 template <class T>
 void stack<T>::push(T data)
    {
       if(top==max-1)
      cout<<\"\\n Stack is full \"<<endl;

       else
      {
         top++;
         stk[top]=data;
      }
    }


 //----------------------------   pop(T)  --------------------------------//


 template <class T>
 T stack<T>::pop()
    {
       T item;


       if(top==-1)
         cout<<\"\\n Stack is empty \"<<endl;

       else
      {
         T item=stk[top];

         top--;
      }

       return item;
    }



 //---------------------------  complex  ---------------------------------//




 //----------------   &operator<<(ostream &,complex &)  ------------------//


 ostream &operator<<(ostream &o,complex &c)
    {
       o<<\"\\n\\t Real Part = \"<<c.real_part<<\"\\t Imaginary Part = \"<<
                             c.imaginary_part<<endl;
       return o;
    }

 main()
    {
       clrscr();


       cout<<\"\\n **********  Integers  ********\"<<endl;

       stack<int> s_1;

       s_1.push(10);
       s_1.push(20);
       s_1.push(30);

       cout<<s_1.pop()<<endl;
       cout<<s_1.pop()<<endl;
       cout<<s_1.pop()<<endl;

       cout<<\"\\n **********  Floats  ********\"<<endl;

       stack<float> s_2;

       s_2.push(1.1);
       s_2.push(2.2);
       s_2.push(3.3);

       cout<<s_2.pop()<<endl;
       cout<<s_2.pop()<<endl;
       cout<<s_2.pop()<<endl;

       cout<<\"\\n **********  Complex Numbers  ********\"<<endl;

       complex c_1(1.5,2.5);
       complex c_2(2.5,3.5);
       complex c_3(3.5,4.5);

       stack<complex> s_3;

       s_3.push(c_1);
       s_3.push(c_2);
       s_3.push(c_3);

       cout<<s_3.pop()<<endl;
       cout<<s_3.pop()<<endl;
       cout<<s_3.pop()<<endl;

       getch();
       return 0;
    }

 
 
Didn't find what you were looking for? Find more on Program to illustrate template classes