关于基于模板实现的链表为什么编译通不过啊

biaoyiddd 2013-08-04 11:42:22
#include <iostream>
#include <string>
using namespace std;
template<class T>
class List{
private:
struct node{
T data;
node* next;
}*head,*tail;
public:
List(){
head=tail=NULL;
}
~List(){
node* curr=head,*p;
while (curr!=NULL)
{
p=curr;
curr=curr->next;
delete p;
}
head=tail=NULL;
}
void inserthead(T *item){
node *p;
p=new node;
p->next=head;
p->data=*item;
head=p;
if(tail==NULL)
tail=p;
}
void inserttail(T * item){
node *p;
p=new node;
p->next=NULL;
p->data=*item;
if(head==NULL)
head=tail=p;
else
tail=p;
}
T get(){
T temp;
node *p=head;
temp=head->data;
if(head==tail)
head=tail=NULL;
else
head=head->next;
delete p;
return temp;
}
};

class Person{
private:
string name;
int score;
public:
Person(string n,int s):name(n),score(s){}
void show(){
cout<<"name is "<<name<<"/n"<<"score is "<<score<<endl;
}
};

void main()
{
Person p1("ldh",90),p2("lm",80),p3("lj",60);
List<int> l;
List<Person> lis=List<Person>();
lis.inserthead(&p1);
lis.inserthead(&p2);
lis.inserttail(&p3);
Person p=lis.get();
p.show();
}
...全文
149 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
max_min_ 2013-08-05
  • 打赏
  • 举报
回复
这段代码看的真心别扭,

List(){
head=tail=NULL;
}
~List(){
node* curr=head,*p;
while (curr!=NULL)
{
p=curr;
curr=curr->next;
delete p;
}
head=tail=NULL;
}
图灵狗 2013-08-05
  • 打赏
  • 举报
回复
代码太乱了!
Inphyy 2013-08-05
  • 打赏
  • 举报
回复
报错很清楚啊,struct node没写构造函数
	
struct node{
    node(){};
    T data;
    node* next;
}*head,*tail;
修改完以后还是会报错 d:\workspaces\vc\test\test\ttt.cpp(47): error C2512: “Person”: 没有合适的默认构造函数可用 你的person类的构造函数为Person(string n,int s):name(n),score(s){} 而你在模板类里面的构造函数,T data 没有传入参数也就是没找到对应构造函数,创建对象失败
biaoyiddd 2013-08-04
  • 打赏
  • 举报
回复
提示的错误是这样的: 1>f:\ldh\workspace\test17\test17\链表.cpp(27): error C2512: “List<T>::node”: 没有合适的默认构造函数可用 1> with 1> [ 1> T=Person 1> ] 1> f:\ldh\workspace\test17\test17\链表.cpp(25): 编译类 模板 成员函数“void List<T>::inserthead(T *)”时 1> with 1> [ 1> T=Person 1> ] 1> f:\ldh\workspace\test17\test17\链表.cpp(72): 参见对正在编译的类 模板 实例化“List<T>”的引用 1> with 1> [ 1> T=Person 1> ] 1> 1>生成失败。 1>

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧