今天这个程序花时间好长啊
有了一点程序的心得
1。一定要先懂得程序的框架,这样才能事半功倍
2。良好的书写习惯是必须的
3。在类里面的函数实现用写在程序最后的显式的方式书写
4。括号要写清楚
5。变量名和类名不要起类似接近的名字,要有代表意义
6。函数的参量是不是指针要清楚
代码如下:
#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
//中间层计数类
class Expr_node {
friend ostream& operator<< (ostream& ,const Expr_node& );
friend class Expr;
public:
int use; //计数器
virtual void print(ostream&) const=0;
protected:
Expr_node():use(1){}
virtual ~Expr_node();
};
// 句柄类
class Expr {
friend ostream& operator<<(ostream&,const Expr&);
public:
Expr_node* p;
Expr(int);
Expr(const string& ,Expr);
Expr(const string& ,Expr ,Expr ) ;
Expr(const Expr& t) { p=t.p;++(p->use);}
Expr& operator=(const Expr& );
~Expr(){if(--p->use==0) delete p;}
};
//下面生成具体的类
class Int_node:public Expr_node{
friend class Expr;
int n;
Int_node(int k):n(k){}
void print(ostream& o) const {o<<n;}
};
class Unary_node:public Expr_node{
friend class Expr;
string op;
Expr opnd; //将Expr_node改为Expr
Unary_node(const string& a,Expr b):op(a),opnd(b){}
void print(ostream& o) const {o<<"("<<op<<opnd<<")";}
};
class Binary_node:public Expr_node{
friend class Expr;
string op;
Expr left; //原来是Expr_node* left;,因加入句柄而改为现在语句
Expr right;
Binary_node(const string& a,Expr b,Expr c):op(a),left(b),right(c){}
void print(ostream& o) const {o<<"("<<left<<op<<right<<")";}
};
//句柄类续
Expr::Expr(int n)
{
p=new Int_node(n);
}
Expr::Expr(const string& op,Expr t)
{
p=new Unary_node(op,t);
}
Expr::Expr(const string& op,Expr left,Expr right)
{
p=new Binary_node(op,left,right);
}
Expr& Expr:: operator=(const Expr& t){
t.p->use++;
if(--p->use==0)
delete p;
p=t.p;
return *this;}
//重载<<
ostream& operator <<(ostream& o,const Expr& t)
{
t.p->print(o);
return o;
}