This example includes the following source files:
In this example:
This header file defines the class template for the class Stack.
#ifndef STACK_H #define STACK_H template <class Item, int size> class Stack { public: void push(Item item); // Push operator Item pop(); // Pop operator int isEmpty(){ return (top==0); // Returns true if empty, otherwise false } Stack() { top = 0; } // Constructor defined inline private: Item stack[size]; // The stack of items int top; // Index to top of stack }; #ifndef __TEMPINC__ // 3 #include "stack.c" // 3 #endif // 3 #endif
This file provides the implementation of the class template for the class Stack.
template <class Item, int size> void Stack<Item,size>::push(Item item) { if (top >= size) throw size; stack[top++] = item; } template <class Item, int size> Item Stack<Item,size>::pop() { if (top <= 0) throw size; Item item = stack[--top]; return(item); }
This header file contains the prototype for the add function, which is used in both stackadd.cpp and stackops.cpp.
void add(Stack<int, 50>& s);
This file provides the implementation of the add function, which is called from the main program.
#include "stack.h" // 1 #include "stackops.h" // 2 void add(Stack<int, 50>& s) { int tot = s.pop() + s.pop(); s.push(tot); return; }
This file creates a Stack object.
#include <iostream.h> #include "stack.h" // 1 #include "stackops.h" // 2 main() { Stack<int, 50> s; // create a stack of ints int left=10, right=20; int sum; s.push(left); // push 10 on the stack s.push(right); // push 20 on the stack add(s); // pop the 2 numbers off the stack // and push the sum onto the stack sum = s.pop(); // pop the sum off the stack cout << "The sum of: " << left << " and: " << right << " is: " << sum << endl; return(0); }