* a和*a和* a的区别

sdaulzh 2019-04-16 09:25:53
如题,这些的区别在哪里?
下面是链栈的部分代码
一开始是push代码中的变量没有定义完全 使用Node<DataType> *s;会报停止运行错 定义完全后就可以执行到底
在LinkStack类中 私有成员 Node<DataType>* top、Node<DataType> *top这么定义,构建没问题 但是运行会报已停止运行框
猜测是析构函数出现错误,把析构函数去掉后就不报错。
但私有成员Node<DataType> * top 这么定义就不会出现错误。
想问一下,这是怎么回事?

#include <iostream>
using namespace std;
template <class DataType>
struct Node{
DataType data;
Node *next;
};
template <class DataType>
class LinkStack{
private:
Node<DataType> * top;
public:
LinkStack(){top=NULL;}
~LinkStack();
void push(DataType x);
DataType pop();
DataType gettop();
int Empty();
};

template <class DataType>
LinkStack<DataType>::~LinkStack(){
Node<DataType> *q = top;
while(q!=NULL){
q = top;
delete q;
top = top -> next;
}
}

template <class DataType>
void LinkStack<DataType>::push(DataType x){
Node<DataType> *s = new Node<DataType>;
//定义变量格式要完全
s -> data = x;
s -> next = top;
top = s;
}

int main(){
cout<<"sdsdsd"<<endl;
LinkStack<string> ls;
cout<<"xxxxxx"<<endl;
ls.push("lzh");
cout<<"sdsd";
cout<<"sldksd";
}
...全文
197 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdaulzh 2019-04-16
  • 打赏
  • 举报
回复
引用 3 楼 636f6c696e 的回复:
随便瞟了眼就发现有问题:
q = top;
delete q;
top = top -> next;

都把top释放了,还访问top->next,这不是野指针么?

确实有问题,主要是while循环的判断条件有问题,清空的是对象ls中的内容,对象q用来辅助清空内容,因此判断的应该是ls中的top.而不是判断q
636f6c696e 2019-04-16
  • 打赏
  • 举报
回复
随便瞟了眼就发现有问题: q = top; delete q; top = top -> next; 都把top释放了,还访问top->next,这不是野指针么?
sdaulzh 2019-04-16
  • 打赏
  • 举报
回复
好像不关定义的事,怎么这个停止运行框有时有,有时没有。
这是codeblock的问题么?
只能怪学校实验室的电脑了诶。
sdaulzh 2019-04-16
  • 打赏
  • 举报
回复
艹,这代码怎么是这样的
我再发一下
#include <iostream>
using namespace std;
template <class DataType>
struct Node{
DataType data;
Node *next;
};
template <class DataType>
class LinkStack{
private:
Node<DataType> * top;
public:
LinkStack(){top=NULL;}
~LinkStack();
void push(DataType x);
DataType pop();
DataType gettop();
int Empty();
};


template <class DataType>
LinkStack<DataType>::~LinkStack(){
Node<DataType> *q = top;
while(q!=NULL){
q = top;
delete q;
top = top -> next;
}
}

template <class DataType>
void LinkStack<DataType>::push(DataType x){
Node<DataType> *s = new Node<DataType>;
//定义变量格式要完全
s -> data = x;
s -> next = top;
top = s;
}

int main(){
cout<<"sdsdsd"<<endl;
LinkStack<string> ls;
cout<<"xxxxxx"<<endl;
ls.push("lzh");
cout<<"sdsd";
cout<<"sldksd";
}

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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