首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于容器里的对象析构有关问题

2013-08-24 
关于容器里的对象析构问题C++学习中。自己写了个程序,容器里装有含指针的对象,遇到了很麻烦的问题,调试发现

关于容器里的对象析构问题
C++学习中。自己写了个程序,容器里装有含指针的对象,遇到了很麻烦的问题,调试发现,容器的对象析构出错了,搞了很久,还是不知道怎么解决,麻烦各位懂的大侠多指教,看看是代码要怎样改更好,先谢谢了。可能描述的不是很好,VC6.0、VS2010都有调试过,详见如下代码,可以直接COPY运行帮看看,万分感谢。

#include <string.h>
#include <iostream>
using namespace std;

class user;
ostream &operator << (ostream &out,user &u);
class user
{
private:
int m_id;
//char m_name[20];
//char m_pw[20];
char *m_name;
char *m_pw;
public:
user(){}
user(int id,char *name,char *pw)//构造函数
{
m_name = new char[20];
m_pw = new char[20];
m_id = id;
strcpy(m_name,name);
strcpy(m_pw,pw);
}
user(user &u)//拷贝构造函数
{
m_name = new char[20];
m_pw = new char[20];
m_id = u.m_id;
strcpy(m_name,u.m_name);
strcpy(m_pw,u.m_pw);
}
user &operator = (user &u)//=运算符重载
{
m_name = new char[20];
m_pw = new char[20];
m_id = u.m_id;
//strcpy(m_name,u.m_name);
//strcpy(m_pw,u.m_pw);
return *this;
}
~user()
{
cout<<"~user..."<<endl;
if(m_name != NULL)
{
delete []m_name;
m_name = NULL;
}
if(m_pw != NULL)
{
delete []m_pw;
m_pw = NULL;
}
}
friend ostream &operator << (ostream &out,user &u);       //输出流运算符重载
};

ostream &operator << (ostream &out,user &u)
{
out<<u.m_id<<" "<<u.m_name<<" "<<u.m_pw;
return out;
}

template <class T>
class Stack
{
private:
T m_Data;
Stack *pNext;            //用于指向下一个节点
Stack *pPre;//用于指向前一个节点
Stack *pHead;
Stack *pTemp;
public:
Stack()//构造函数
{
pNext = 0;
pPre = 0;
pHead = 0;
pTemp =pHead;
}
void Push(T data)//入栈,双向循环链栈
{
if(pHead == 0)
{
printf("\n\t\t空链栈!您将增加第一条数据。\n");
}
Stack *pNew = new Stack;  //新结点产生

pNew ->m_Data = data;

pNew ->pNext = pNew;                     //指针域指向自己


pNew ->pPre = pNew;
pNew ->pHead = 0;

if(pHead == NULL)
{
pHead = pNew;
printf("\n\t\t入栈成功!\n");
return ;
}
//在头节点前(也就是循环栈的尾巴)加入新节点
pNew ->pNext = pHead;
pNew ->pPre = pHead ->pPre;
pHead ->pPre ->pNext = pNew;
pHead ->pPre = pNew;

printf("\n\t\t入栈成功!\n");
}

void SearchLnkStack()   //遍历链栈
{
Stack *pLnk = pHead;
if(NULL == pLnk)
{
printf("\t\t空链栈!\n");
return;
}
while(1)
{
//pLink = pLink ->pPrePoint;            //逆向输出
cout<<"\t\t"<<pLnk ->m_Data<<endl;
pLnk = pLnk ->pNext;       //正向输出
if(pHead == pLnk)
break;
}
}
~Stack()
{
cout<<"~Stack..."<<endl;
}
};

int main()
{
Stack<user> s1;
user u1(1,"lion","123456");
//user u2(2,"tiger","123456");
//user u3(3,"mirror","123456");
s1.Push(u1);
//s1.Push(u2);
//s1.Push(u3);
//s1.Push(1);
//s1.Push(2);
//s1.Push(3);
s1.SearchLnkStack();
return 0;    //析构~Stack后,s1里的pHead栈中的m_data里的指针释放时出错!
}

觉厉

热点排行