I am learning the design pattern now and I read the book Ruminations on C++. The following example is how to use the handle class to do some application.
#include <iostream>
#include <string>
#include <utility>
using namespace std;
class Expr_node;
class Int_node;
class Unary_node;
class Binary_node;
class Expr {
friend ostream& operator<<(ostream&, const Expr&);
Expr_node* p;
public:
Expr(int);
Expr(const string&, Expr);
Expr(const string&, Expr, Expr);
Expr(const Expr&);
Expr& operator=(const Expr&);
};
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);
}
class Expr_node {
friend ostream& operator<< (ostream&, const Expr_node&);
protected:
virtual void print(ostream&) const = 0;
virtual ~Expr_node() { }
};
ostream& operator<< (ostream& o, const Expr_node& e) {
e.print(o);
return o;
}
class Int_node: public Expr_node {
friend class Expr;
int n;
explicit Int_node(int k) : n(k) {}
void print(ostream& o) const override { o << n;}
};
class Unary_node: public Expr_node {
friend class Expr;
string op;
Expr opnd;
Unary_node(const string& a, const Expr& b): op(a), opnd(b) {}
void print(ostream& o) const override {o << "(" << op << *opnd << ")";}
};
class Binary_node: public Expr_node {
friend class Expr;
string op;
Expr left;
Expr right;
Binary_node(const string& a, const Expr& b, const Expr& c): op(a), left(b), right(c) {}
void print(ostream& o) const override { o << "(" << left << op << right << ")";}
};
In this example, I want to implement three different kinds of operation based on inheritance from Expr_node
class. It is obvious that the Int_node
is not well defined until its full definition. I am not sure how to solve this problem. It seems that there are a lot of errors involved in this book.