读书人

模板的链表解决方法

发布时间: 2013-02-05 10:40:57 作者: rapoo

模板的链表
我是要建立一个模板的链表,但是加了b1.push(i); 就报错; 不知道怎么改
#include<iostream>
using namespace std;
template <class T>
class stack;
template <class T>
class node
{
friend class stack<T>;//这里忘记写类型了
public:
node()//这个构造函数没有用
{
cout<<"123"<<endl;
}
node(T _data)
{
next = NULL;
cout<<"1"<<endl;
}
private:
T data;
node <T>*next;
};
template <class T>
class stack
{
public:
stack()
{
head=NULL;
}
void push(T _data)//建立链表
{
node<T>*p=new T;
p->data=_data;
p->next=NULL;
if(head==NULL)
{
head =curr=p;
}
else
{
curr->next=p;
curr = p;
}
}
void show()
{
node<T>*p1=head;
while(1)
{

cout<<p1->data<<endl;
if(p1->next==NULL)
{
break;
}
p1=p1->next;
}
}
private:
node <T>*head;
node <T>*curr;
};
int main()
{
node<int> a1;//调用无参构造函数
node<int> a2(1);//调用了有参构造函数
stack<int> b1;
int i;
for(i=0;i<10;i++)
{
b1.push(i);
}
b1.show();
return 0;
}

[解决办法]
这句


node<T>*p=new T;

改成这样

node<T>*p=new node<T>;

再试一下.

读书人网 >C++

热点推荐