C++沉思录读书笔记(8章)-一个面向对象程序范例(二)

2014-11-24 12:36:28 · 作者: · 浏览: 1
ete p;

}

};

class Int_node: public Expr_node

{

private:

int n;

public:

Int_node(int k):n(k) {}

void print(ostream &o) const

{

o << n;

}

};

class Unary_node: public Expr_node

{

private:

//friend class Expr;

string op;

Expr opnd;

public:

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

{

private:

//friend class Expr;

string op;

Expr left;

Expr right;

public:

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 &e)

{

e.p->print(o);

return o;

}

void main()

{

Expr t = Expr("*",

Expr("-", Expr(5)),

Expr("+", Expr(3), Expr(4)));

cout << t << endl;

}

五 总结

这个例子很好的展示了面向对象的三个要素,这样设计出的类具有很好的扩展性,比如再增加有多个子节点的节点,只要添加个新类,然后在Expr中添加个新构造函数就行了。用户完全不必知道底层的代码是怎么实现的。以后面对问题的时候要好好的借鉴这种思想!

作者 yucan1001