c++新手在这里。我目前正在尝试编写一个涉及模板堆栈的程序,该程序可以处理两种单独的数据类型,int 和 Student 对象。虽然程序的堆栈逻辑工作正常,但我不确定如何为每种数据类型打印堆栈顶部的值。现在我有两个可能的想法,为一个类重载'<<' 运算符(我不确定是哪一个)或为 TopStack() 编写重载函数(即template <> int Stack<int>::TopStack() const
)。我已经实现了后者,但不正确。有谁知道实现这一目标的最有效方法是什么?我愿意接受任何建议。
我将发布我的代码的相关部分,以便您可以看到我在说什么。
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;