以下代码中,为什么总是编译失败,而且结构体里面那个template T 不识别!

/*2.a 实现栈模板类
要求:1)用链表形式来存储栈数据
2)实现栈的常用函数
*/
#include <iostream>
using namespace std;
template <class T>
class Mystack{
  struct Node
  { T data;
  Node *next;
  };
   Node *head;
public:
Mystack()
{
head=NULL;
}
~Mystack()
{
while(head!=NULL)
{
Node*p=head;
head=p->next;
delete p;
}
}
void input()
{
cout<<"开始输入数据"<<endl;
T x;
cin>>x;
while(x!=-1)
{
Node *p=new Node ;
p->data=x;
p->next=head;
head=p;
cin>>x;
}
}

T push(T n)
{
T num=n;
Node *p=new Node;
p->data=num;
p->next=NULL;
if(head==NULL)
{
head=p;
return num;
}
else
{
p->next=head;
head=p;
return num;
}
}
T pop()
{
if(head==NULL)
return -1;
else
{
T x=head->data;
Node *p=head;
head=head->next;
delete p;
return x;
}
}
void display()
{
Node *p=head;
for(;p!=NULL;p=p->next)
cout<<p->data<<" ";
cout<<endl;
}
void gettop()
{
if(head==NULL)
cout<<"the stack is empty!"<<endl;
else
cout<<"the top number is "<<head->data<<endl;
}
bool empty()
{
if(head==NULL)
return true;
else
return false;
}
};
void main()
{
Mystack<int> h;
cout<<"开始输入数据(为int型)"<<endl;
h.input();
h.gettop();
int x;
cout<<"输入进栈的数据(为int型)"<<endl;
cin>>x;
if(h.push(x)==x)
cout<<"进栈成功!"<<endl;
cout<<"进栈之后的数据输出:"<<endl;
h.display();
if(!(h.pop()==-1))
{
cout<<"出栈成功!"<<endl;
cout<<"出栈之后的数据输出:"<<endl;
h.display();
}
else
cout<<"栈内没有数据"<<endl;
cout<<endl;
cout<<"**************************************"<<endl;

Mystack<double> t;
cout<<"开始输入数据(为double型)"<<endl;
t.input();
t.gettop();
double y;
cout<<"输入进栈的数据(为double型)"<<endl;
cin>>y;
if(t.push(y)==y)
cout<<"进栈成功!"<<endl;
cout<<"进栈之后的数据输出:"<<endl;
t.display();
if(!(t.pop()==-1))
{
cout<<"出栈成功!"<<endl;
cout<<"出栈之后的数据输出:"<<endl;
t.display();
}
else
cout<<"栈内没有数据"<<endl;
}


墨色风雨
浏览 209回答 2
2回答

慕的地6264312

T是指一种类型 比如string 你只写T当然不会识别了

素胚勾勒不出你

在结构体的那里也加上、template<typename T>
打开App,查看更多内容
随时随地看视频慕课网APP