|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 xxxvvv311 于 2014-3-20 06:23 编辑
#include <iostream>
using namespace std;
class Expr;
class Expr_node{
friend ostream& operator<<
(ostream&,const Expr&);
friend class Expr;
public :
virtual void print(ostream&)const=0;
int use;
Expr_node():use(1){}
virtual ~Expr_node() {}
};
class Expr {
friend ostream& operator<<
(ostream&,const Expr&);
public:
Expr_node* p;
Expr(int);
Expr(const char*,Expr);
Expr(const char*,Expr,Expr);
Expr(const Expr&t){p=t.p;++p->use;}
Expr& operator=(const Expr&);
~Expr(){delete p;}
};
Expr& Expr::operator=(const Expr& rhs){
rhs.p->use++;
if (--p->use==0)
delete p;
p=rhs.p;
return *this;
}
ostream& operator<<(ostream&o,const Expr& e){
e.p->print(o);
return o;
}
class Int_node:public Expr_node{
friend class Expr ;
public :
int n;
Int_node(int k):n(k){}
void print (ostream& o)const {o<<n;}
};
class Unary_node:public Expr_node{
friend class Expr ;
public :
const char* op;
Expr opnd;
Unary_node(const char* a,Expr b):op(a),opnd(b){}
void print (ostream& o)const{o<<"("<<op<<opnd<<")";}
};
class Binary_node:public Expr_node{
friend class Expr ;
public:
const char* op;
Expr left;
Expr right;
Binary_node( const char*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 char*op,Expr t){p=new Unary_node(op,t);}
Expr::Expr(const char*op,Expr left,Expr right){p=new Binary_node(op,left,right);}
int main()
{
Expr t=Expr("*",Expr("-", 5),Expr("+", 3,6));
cout<<t<< endl;
cin.get();
}
我是菜鸟,找不出问题了,求助 |
|