node.h
#ifndef NODE_H
#define NODE_H
#include "expr.h"
#include <string>
#include <iostream>
using namespace std;
class Expr_node
{
public:
Expr_node(): use(1) {}
virtual ~Expr_node() {}
virtual void print(ostream&) const = 0;
private:
int use;
friend class Expr;
friend ostream& operator <<(ostream& o, const Expr_node& e);
};
class Int_node: public Expr_node
{
public:
Int_node(int k): n(k) {}
private:
friend class Expr;
int n;
void print(ostream& o) const { o << n; }
};
class Unary_node: public Expr_node
{
public:
Unary_node(const string& a, Expr b)
: op(a), opend(b) {}
private:
string op;
Expr opend;
void print(ostream& o) const
{
o << "(" << op << opend << ")";
}
friend class Expr;
};
class Binary_node: public Expr_node
{
public:
Binary_node(const string a, Expr b, Expr c)
:op(a), left(b), right(c) {}
private:
void print(ostream& o) const
{
o << "(" << left << op << right << ")";
}
friend class Expr;
string op;
Expr left;
Expr right;
};
#endif // NODE_H
expr.h
#ifndef EXPR_H
#define EXPR_H
#include <string>
#include <iostream>
using namespace std;
class Expr_node;
//句柄类
class Expr
{
friend ostream& operator<<(ostream& o, const Expr& e);
Expr_node* p;
public:
Expr(int data);
Expr(const string& op, Expr e);
Expr(const string& op, Expr a, Expr b);
Expr(const Expr& e);
Expr& operator=(const Expr& rhs);
~Expr();
};
#endif // EXPR_H
expr.cpp
#include "expr.h"
#include "node.h"
Expr::Expr(int data)
{
p = new Int_node(data);
}
Expr::Expr(const string& op, Expr e)
{
p = new Unary_node(op, e);
}
Expr::Expr(const string& op, Expr a, Expr b)
{
p = new Binary_node(op, a, b);
}
Expr::Expr(const Expr& e)
{
p = e.p;
++p->use;
}
Expr::~Expr()
{
if (--p->use == 0)
{
delete p;
}
}
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;
}
main.cpp
#include <iostream>
#include "Expr.h"
#include <string>
using namespace std;
int main()
{
Expr t = Expr("*", Expr("-", 5), Expr("+", 3, 4));
cout << t << endl;
t = Expr("*", t, t);
cout << t <<endl;
return 0;
}
输出:
((-5)*(3+4))
(((-5)*(3+4))*((-5)*(3+4)))
写这段代码也是一波三折啊。
详见:http://bbs.csdn.net/topics/390664205?page=1#post-396299826