【发布时间】:2021-07-12 16:26:48
【问题描述】:
我目前正在编写一个堆栈类,它可以与不同的数据类型一起使用,但是当我想将不同的数据类型弹出回主范围并将其存储在另一个变量中时,问题就来了,在类函数中我可以使用模板来解决这个问题,但是好像主范围不能使用模板,有没有办法可以在main中声明一个不同数据类型的变量?
int main() {
int x, y;
Stack <int> si(12);
Stack <char> sc(10);
Stack <string> ss(5);
ss.Push("John");
ss.Push("Peter");
ss.Push("Mary");
y = ss.Pop();
cout << y;
cout << ss;
si.Push(9);
si.Push(8);
si.Push(7);
y = si.Pop();
cout << y;
cout << si;
sc.Push('A');
sc.Push('B');
sc.Push('D');
sc.Push('E');
y = sc.Pop();
cout << y;
cout << sc;
return 0;
我想让你存储任何类型的数据,这可能吗? 这是弹出功能
template<class KeyType>
KeyType &Stack <KeyType>::Pop(void)
{
KeyType x;
if (IsEmpty())
StackEmpty();
else
{
x = stack[top];
stack[top] = -1;
top--;
}
return x;
}
【问题讨论】:
-
似乎 y 被声明为整数,但你弹出一个字符串 y = ss.Pop();
-
您可以完全跳过存储 pop 操作的输出,只像
std::cout << ss.Pop()一样将它们打印出来,巧妙地避免了重用变量的问题... -
您的
Pop函数返回一个悬空引用,即UB。你不能像那样返回对局部变量的引用。
标签: c++ class templates types stack