新手类模板析构函数求解

fxfxfxfxw 2016-05-18 07:06:05
#include<iostream>
using namespace std;
template<typename T>
struct Node
{
T data;
Node<T> *next;
};
template<class T>
class Set
{
friend ostream& operator<< <>(ostream& out, const Set<T>& s);
public:
Set()
{
head = new Node<T>;
head->next = NULL;
}
Set(const T& s)
{
Node<T> *p, *pnew, *ptail;
p = s.head->next;
ptail = head;
while (p)
{
pnew = new Node<T>;
ptail->next = pnew;
pnew->date = p->data;
p = p->next;
ptail = pnew;
}
ptail->next = NULL;
}
~Set()
{
Node<T>* p;
while (head!=NULL)
{
p = head->next;
delete head;
head = p;
}
}
void print();
void in();
private:
Node<T> *head;
};
template<typename T>
void Set<T>::in()
{
int i, n;
Node<T> *p, *pnew;
p = head;
cout << "input number" << endl;
cin >> n;
for (i = 0; i < n; i++)
{
pnew = new Node<T>;
cin >> pnew->data;
p->next = pnew;
p = pnew;
}
p->next = NULL;
}
template<typename T>
ostream& operator<<(ostream& out, const Set<T>& s)
{
Node<T> *p;
p = s.head->next;
while (p)
{
cout << p->data << ' ';
p = p->next;
}
return out;
}
void main()
{
Set<int> s;
s.in();
cout << s<<endl;
Set<int> a(s);
cout << a << endl;
}

编译出错,把析构函数注释就成功了,百思不得旗解,感觉析构写对的啊,
...全文
178 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhang_qi123 2016-05-18
  • 打赏
  • 举报
回复
你的拷贝构造函数写错了,格式也是错误的,拷贝构造的参数应该是 const Set<T>&s。你的程序在执行a(s)的时候调用的是默认的拷贝构造函数,这个默认的是浅拷贝,只是把地址拷贝了,内容没有拷贝,所以在析构的时候,对一个对象析构了两次,所以程序会崩溃!要么重写拷贝构造,要么删除给对象a初始化的那条语句!
fxfxfxfxw 2016-05-18
  • 打赏
  • 举报
回复
引用 1 楼 dustpg 的回复:
复制构造函数参数 Set(const T& s) -> Set(const Set<T>& s) 当然,这函数还是很有问题,比如date与data,还有头指针的初始化,不过这让lz自己解决的好
太感谢了,只因为自己粗心大意浪费你时间
dustpg 2016-05-18
  • 打赏
  • 举报
回复
复制构造函数参数 Set(const T& s) -> Set(const Set<T>& s) 当然,这函数还是很有问题,比如date与data,还有头指针的初始化,不过这让lz自己解决的好

65,187

社区成员

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

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