面向对象的程序范例(一)

时间:2021-09-04
本文章向大家介绍面向对象的程序范例(一),主要包括面向对象的程序范例(一)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

功能:打印表达式

技术:句柄、继承

代码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Expr_node;
 5 
 6 // 句柄类
 7 class Expr
 8 {
 9     friend ostream& operator<< (ostream& o, const Expr& t);
10     Expr_node* p;
11 public:
12     Expr():p(0){}
13     Expr(int n);
14     Expr(const string& op, const Expr& t);
15     Expr(const string& op, const Expr& left, const Expr& right);
16     Expr(const Expr& t);
17     Expr& operator=(const Expr&);
18     ~Expr();
19 };
20 
21 // 用于派生实际类型的公共基类,表示“结点”
22 class Expr_node
23 {
24     friend class Expr;
25     int use;
26 protected:
27     Expr_node():use(1){}
28     virtual ~Expr_node() {};
29 public:
30     virtual void print(ostream&)const=0;
31 };
32 
33 // 存放数值的子类
34 class Int_node:public Expr_node
35 {
36     friend class Expr;
37     int n;
38     Int_node(int k):n(k){}
39 public:
40     void print(ostream& o)const{o<<n;}
41 };
42 
43 // 存放符号数的类
44 class Unary_node:public Expr_node
45 {
46     friend class Expr;
47     string op;
48     Expr opnd;
49     Unary_node(const string& a, const Expr& b):op(a),opnd(b){}
50 public:
51     void print(ostream& o)const{o<<"("<<op<<opnd<<")";}
52 };
53 
54 // 存放符号和左右表达式的子类
55 class Binary_node:public Expr_node
56 {
57     friend class Expr;
58     string op;
59     Expr left;
60     Expr right;
61     Binary_node(const string& a, const Expr& b, const Expr& c):op(a),left(b),right(c){}
62 public:
63     void print(ostream& o)const{o<<"("<<left<<op<<right<<")";}
64 };
65 
66 Expr::Expr(int n){p=new Int_node(n);}
67 Expr::Expr(const string& op, const Expr& t){p = new Unary_node(op,t);}
68 Expr::Expr(const string& op, const Expr& left, const Expr& right){p = new Binary_node(op,left,right);}
69 Expr::Expr(const Expr& t):p(t.p){++(p->use);}
70 Expr& Expr::operator=(const Expr& rhs)
71 {
72     rhs.p->use++;
73     if (p&&--(p->use)==0)
74         delete p;
75     p = rhs.p;
76     return *this;
77 }
78 Expr::~Expr() {if (--p->use==0) delete p;}
79 
80 ostream& operator<< (ostream& o, const Expr& t)
81 {
82     t.p->print(o);
83     return o;
84 }
85 
86 int main()
87 {
88     Expr t("*", Expr("-", 5), Expr("+", 3, 4));
89     cout<<t<<endl;
90     t = Expr("*", t, t);
91     cout<<t<<endl;
92     return 0;
93 }

 示意图:

  

 结果:

  ((-5)*(3+4))

  ((((-5)*(3+4)))*(((-5)*(3+4))))

原文地址:https://www.cnblogs.com/suui90/p/15227949.html