This example includes the following source files:
#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
};
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);
}
#endif
Here is the revised example that compiles successfully
with -qtempinc: #ifndef STACK_H
#define STACK_H
#ifndef __TEMPINC__
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
};
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);
}
#endif
This header file contains the prototype for the add function, which is used in both stackadd.cpp and stackops.cpp.
#ifndef STACKOPS_H #define STACKOPS_H #include "stack.h" void add(Stack<int, 50>& s); #endif
This file provides the implementation of the add function, which is called from the main program.
#include "stack.h"
#include "stackops.h"
void add(Stack<int, 50>& s) {
int tot = s.pop() + s.pop();
s.push(tot);
return;
}
This file creates a Stack object.
#include <iostream>
#include "stack.h"
#include "stackops.h"
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);
}