《C++沉思录》的一个例子

C++沉思录》的一个例子

 

  用VC6.0编译了《C++沉思录》第8章的例子,是用树来表示算术表达式。一个重要的修改是把Stringstring,这是因为Stringvcl内建类型,而VC中没有这个类型。

#include <iostream>

#include <string>

using namespace std;

 

class Expr

{

    friend ostream& operator << ( ostream&, const Expr& );

    friend class  Expr_node;

    Expr_node *p;

public:

    Expr (int n);

    Expr (const string& op, Expr t );

    Expr (const string& op , Expr r, Expr l);

 

    Expr (const Expr &);

    Expr& operator = (const Expr &);

    ~Expr ( ) ;

};

 

class Expr_node

{

    friend ostream& operator << ( ostream& os, const Expr& rhs);

    friend ostream& operator << ( ostream&, const Expr_node& );

    friend class Expr;

    int use;

protected:

    Expr_node():use(1){}

    virtual void print ( ostream& )const = 0;

    virtual ~Expr_node ( ){}

};

 

ostream& operator << (ostream& o, const Expr_node& t)

{

    t.print (o);

    return o;

}

 

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;

    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 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<<")";

    }

};

 

ostream& operator << ( ostream& o, const Expr& t)

{

    t.p->print (o);

    return o;

}

 

Expr::Expr ( const Expr& t)

{

    p=t.p;

    ++(p->use);

}

 

Expr& Expr::operator = ( const Expr& t)

{

    (t.p->use)++;

    if(--(p->use)==0)    delete p;

    p=t.p;

    return *this;

}

 

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 r, Expr l) {p = new Binary_node (op, r,l);}

Expr::~Expr( ) {if (--p->use ==0) delete p;}

                                                      

void main()

{

    Expr t=Expr("*",Expr("-",5),Expr("+",3,4));

    cout<<t<<endl;

}

 

相关帖子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值