Сейчас я изучаю шаблон проектирования и читаю книгу «Размышления на С ++». В следующем примере показано, как использовать класс handle для какого-либо приложения.
#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 << ")";}
};
В этом примере я хочу реализовать три различных типа операций, основанных на наследовании от класса Expr_node
. Очевидно, что Int_node
не является четко определенным до его полного определения. Я не уверен, как решить эту проблему. Кажется, в этой книге много ошибок.