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;
最佳答案
int TopStack() const; // return data from the top of the stack
应该是
DataType TopStack() const; // return data from the top of the stack
因为数据的类型随栈的类型而变化。
实现了这样的事情:
template<typename DataType>
DataType Stack<DataType>::TopStack() const
{
Assert(top != nullptr);
if (top == nullptr)
return DataType();
return top->data;
}
但是,你的类(class)是做什么的std::stack<T>
不呢?甚至 std::vector<T>
(有趣的是,通常堆栈比 stack
更好)。
正在使用您的 Stack<DataType>
的代码将知道数据的类型,要么是因为它正在与之交谈的变量的类型,要么是它本身具有的模板参数。添加 operator<<
为您的 Student 类重载,因此您可以打印它们而无需跳过任何特殊的箍。
如果发现重载 operator<<
可怕的是,你可以写一个独立的Print
函数 int
和 Student const&
过载。
关于c++ - 在两个模板堆栈之上打印不同的数据类型 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13349306/