码迷,mamicode.com
首页 > 编程语言 > 详细

C++沉思录第8章程序,正确运行

时间:2014-10-08 00:23:24      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   sp   div   c   

#include <iostream>
#include <string>

using namespace std;

class Expr_node{
    //friend ostream& operator<<(ostream&, const Expr_node&);
    friend class Expr;
private:
    int use;
public:
    Expr_node(): use(1) { }
    virtual void print(ostream&) const = 0;
    virtual ~Expr_node() { }
};

/*
ostream& operator<<(ostream& o, const Expr_node& e){
    e.print(o);
    return o;
}
*/

class Expr{
    friend ostream& operator<<(ostream&, const Expr&);
private:
    Expr_node *p;
public:
    Expr(int);
    Expr(const string&, Expr);
    Expr(const string&, Expr, Expr);
    Expr(const Expr&);
    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;
    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 << ")";}
};

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(const Expr& t){
    p = t.p;
    ++p->use;
}
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& t){
    (t.p)->print(o);
    return o;
}

int main()
{
    Expr t = Expr("*", Expr("-",5), Expr("+", 3, 4));
    cout << t << endl;
    return 0;
}

 

C++沉思录第8章程序,正确运行

标签:style   blog   color   io   os   ar   sp   div   c   

原文地址:http://www.cnblogs.com/simplewonder/p/4009981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!