各位好:
我是c++的初学者,写了一段程序,主要是用来匹配花括号的,并指明在什么位置匹配,什么位置不匹配,不过在执行时出现了一点问题,请指点一下,谢谢!
/****************myBraceRules*********************/
1.BraceNode.cc
#include "myBraceNode.h"
BraceNode * OpeBrace::head;
BraceNode::BraceNode()
{next=NULL;}
OpeBrace::OpeBrace()
{
head=NULL;
}
void OpeBrace::push(BraceNode &n,char &ch)
{
if(head==NULL)
{
n.next=NULL;
n.ch=ch;
head=&n;
}
else
{
n.ch=ch;
n.next=head->next;
head->next=&n;
}
}
char * OpeBrace::pop()
{
if(head!=NULL)
{
BraceNode *tmp=head;
if(tmp->ch=={)
{
head=head->next;
delete tmp;
return "Match";//我跟踪时,系统到此就断掉了,报告"User
//BreakPoint called from code at 0x77f7x570"
//请指点!
}
}
else
{return "Error";}
return "Error";
}
void OpeBrace::Delete()
{
while(head!=NULL)
{
BraceNode * t=head->next;
head=t->next;
delete t;
}
}
//myBraceNode.h
#include <iostream>
using namespace std;
class BraceNode
{
private:
char ch;
BraceNode * next;
public:
BraceNode();
friend class OpeBrace;
};
class OpeBrace
{
private:
static BraceNode * head;
public:
OpeBrace();
void push(BraceNode &,char &);
void Delete();
char * pop();
};
//Main_BraceNode.cc
#include "myBraceNode.h"
#include <string.h>
static OpeBrace OB;
void main()
{
char ch;
int i=0;
int count=0;
cout<<"Please Enter chars including {/}:"<<endl;
while(cin>>ch)
{
if(ch==97)
{
if(count==0)
{
cout<<"There is no { or }"<<endl;
}
break;
}
BraceNode n;
if(ch=={)
{
OB.push(n,ch);
count++;
}
if(ch==})
{
//OpeBrace Opop;
char * Recieve=new char[10];
strcpy(Recieve,OB.pop());
cout<<Recieve<<" at "<<i<<endl;
delete Recieve;
count++;
}
i++;
}
}
在你跟踪出错的地方,将head赋予自动变量tmp后,两者都指向同一内存空间,在此删除tmp后,
head就成了悬空指针,也就是说你改变了静态变量OB的内容,可去掉"delete tmp"这一句,这不会造成内存泄漏,只要超出该自动变量的作用域,其会自动销毁.
老师曾教过我一个技巧,你也不妨试一试:
不要一次把程序敲出来,否则,程序几百行后,一个‘;’少了会引起很多错的,有不少
时间才能查出来的,更别说复杂些的错了,你说呢?
所以,我们要写一小段就编译一下,
确保无误后在继续,这样,写完后也就可以运行了。
你犯了“大炮打蚊子”的错误。 学习C++固然要练习对象,但是程序设计讲究用最简单的方法解决问题。 对于{}匹配,如果你不想使用循环,顶多是个递归。 建议用经典题目练习类对象,如:点、线、多边形、椭圆。