- 论坛徽章:
- 0
|
#include <iostream>
#include <string>
using namespace std;
class Expr;
class Expr_node
{
public:
virtual void print(ostream&) const = 0;
protected:
friend ostream& operator<<(ostream& o, const Expr_node& e)
{
e.print(o);
return o;
}
friend class Expr;
int use;
Expr_node(): use(1){ };
virtual ~Expr_node(){ };
};
class Expr
{
private:
friend ostream& operator<<(ostream& o, const Expr& e)
{
e.p->print(o);
return o;
}
protected:
Expr_node* p;
friend class Expr_node;
public:
Expr(int);
Expr(const string&, Expr);
Expr(const Expr&);
Expr& operator=(const Expr&);
~Expr();
};
class Int_node: public Expr_node
{
public:
friend class Expr;
int n;
Int_node(int k): n(k){ }
void print(ostream& o) const
{ o << n; }
};
class Unary_node: public Expr_node
{
public:
friend class Expr;
string op;
Expr uni;
Unary_node(string a, Expr b):op(a), uni(b){ };
void print(ostream& o) const
{
o << "(" << op << uni << ")";
}
};
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 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;
};
Expr::~Expr()
{ delete p;}
int main()
{
string plus = "+";
Expr *t;
t = new Expr(5);
cout << *t <<endl;
Expr s(*t);
cout << Expr(plus,s )<< endl;
return 0;
}
|
|
|