c++ novice here. I’m currently trying to write a program involving templated stacks that can handle two separate data types, int and Student objects. While the stack logic of the program works fine, I’m not sure how to go about printing the value at the top of the stack for each data type. Right now I have two possible ideas, overload the ‘<<‘ operator for a class (which one, I’m not sure) or write overloaded functions for TopStack() (i.e. template <> int Stack<int>::TopStack() const). I have the latter implemented, but not correctly. Does anyone know what the most efficient way to accomplish this is? I’m open to any suggestions.
I’ll post the relevant parts of my code so you can see what I’m talking about.
template <class DataType>
struct StackNode
{
DataType data; // data can be of any type
StackNode<DataType> *next; // point to the next node
};
template <class DataType>
class Stack
{
private:
StackNode<DataType> *top; // point to the top node of the stack
int maxSize; // maximum stack size
int numNodes; // number of nodes in the stack
public:
Stack(); // constructor, create a stack with size 10
~Stack(); // destructor
bool isEmpty() const { return (top == 0); } // check if the stack is empty
bool isFull() const { return (numNodes == maxSize); } // check if the stack is full
void Push(const DataType &elem); // push a node onto the top of the stack
void Pop(); // pop a node from the top of the stack
int TopStack() const; // return data from the top of the stack
};
struct Students
{
char lastName[20]; // student's last name
char firstName[20]; // student's first name
int IDNumber; // student ID #
Students(); // constructor
void PrintStudent(); // print a student's information
};
void Students::PrintStudent()
{
cout << "\nID# " << this->IDNumber << " - " << this->lastName << ", "
<< this->firstName << endl;
}
// in main() snippet
// if the user asks for top of stack
case 3:
if (!intStack) // I use a boolean to switch the stack being accessed
sstack.TopStack(); // Student stack
else if (intStack)
istack.TopStack(); // Int stack
break;
should be
because the type of the data varies with the type of the stack.
Implemented something like this:
However, what does your class do that
std::stack<T>does not do? Or evenstd::vector<T>(which is, amusingly enough, usually a better stack thanstack).The code that is using your
Stack<DataType>will know the type of the data, either because of the type of the variable it is talking to, or a template parameter it itself has. Add aoperator<<overload for your Student class, so you can print them without jumping through any special hoops.If you find overloading
operator<<to be scary, you could write a free-standingPrintfunction withintandStudent const&overloads.