智能指针-虚析构函数-基类指针访问子类方法

 “计算机科学领域的任何问题都可以通过增加一个间接的中间层来解决” 

“Any problem  in computer science can be solved by anther layer of indirection.”
                              ——David Wheeler(剑桥大学计算机科学教授)
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Fa
 6 {
 7 public:
 8     virtual void Show()
 9     {
10         cout << "father show" << endl;
11     }
12     virtual ~Fa()
13     {
14         cout << "father destructor" << endl;
15     }
16 };
17 
18 class Tclass :public Fa
19 {
20     float pa;
21     double pb;
22     string name;
23     int age;
24 public:
25     Tclass(float pa = 1.0, double pb = 2.0, string name = "all", int age = 20)
26     {
27         this->pa = pa;
28         this->pb = pb;
29         this->name = name;
30         this->age = age;
31     }
32     void Show() override
33     {
34         std::cout << pa << " " << pb << " " << name << " " << age << endl;
35     }
36 
37     ~Tclass()
38     {
39         cout << "call Tclass destructor" << endl;
40     }
41 };
42 class Tcb :public Fa
43 {
44 public:
45     void Show()override
46     {
47         cout << "Tcb show" << endl;
48     }
49     ~Tcb()
50     {
51         cout << "call Tcb destructor" << endl;
52     }
53 };
54 class Shhanlde
55 {
56     Fa* ta;
57 public:
58     Shhanlde(Tclass *tcls)
59     {
60         ta = tcls;
61     }
62     Shhanlde(Tcb *tcls)
63     {
64         ta = tcls;
65     }
66     Fa* GetPt()
67     {
68         return ta;
69     }
70 
71     ~Shhanlde()
72     {
73         delete ta;
74     }
75 };
76 
77 int main()
78 {
79     {
80         shared_ptr<Shhanlde> tc = make_shared<Shhanlde>(new Tclass());
81         tc->GetPt()->Show();
82         tc = make_shared<Shhanlde>(new Tcb());
83         tc->GetPt()->Show();
84     }
85 
86     cout << "test" << endl;
87     return 0;
88 }

 

posted @ 2022-05-09 11:31  小小林林  阅读(73)  评论(0编辑  收藏  举报