模板的继承多态以及多继承多态
1 /* 模板的继承多态以及多继承多态 */
2
3 #include<iostream>
4
5 using namespace std;
6
7 template <class T>
8 class myclass
9 {
10 public:
11 myclass(T a,T b):x(a),y(b)
12 {
13
14 }
15
16 ~myclass()
17 {
18
19 }
20
21 virtual void print()
22 {
23 cout << "virtual void print()" << endl;
24 }
25
26 T getx()
27 {
28 return this->x;
29 }
30
31 T gety()
32 {
33 return this->y;
34 }
35 private:
36 T x;
37 T y;
38 };
39
40
41 template <class NT>
42 class newclass : public myclass<NT>
43 {
44 public:
45 newclass(NT x1,NT y1):myclass(x1,y1)
46 {
47
48 }
49
50 void print()
51 {
52 cout << typeid(*this).name << endl;
53 cout << getx() << " " << gety() << endl;
54 }
55
56 };
57
58 void main()
59 {
60
61 // myclass<double> *p = new myclass<double>(10.9,7.8);
62
63 newclass<double> *p = new newclass<double>(1.9,5.5);
64 p->print();
65
66 // 模板基类指针指向派生模板类的对象,类型必须一致
67 myclass<double> *p = new newclass<double>(1.9,5.5);
68 p->print();
69
70
71 newclass<double> *p = nullptr ;//= new newclass<double>(1.9,5.5);
72 p->print();
73
74
75
76 cin.get();
77 }
模板抽象类:
1 /* 模板抽象类 */
2
3 #include<iostream>
4 #include<cstdlib>
5
6 using namespace std;
7
8 // 模板抽象类
9 template<class T>
10 class runclass
11 {
12 public:
13 virtual void print() = 0;// 纯虚函数
14 public:
15 T x;
16 T y;
17
18 };
19
20
21 template<class T>
22 class runitclass
23 {
24 public:
25 virtual void run() = 0;
26 T z;
27 char *cmd;
28
29 };
30
31 // 多继承主要用途是拓展接口
32 template<class NT>
33 class runclassB : public runclass<NT>,public runitclass<NT>
34 {
35 public:
36 void print()
37 {
38 cout << x << y << endl;
39 }
40
41 void run()
42 {
43 cout << typeid(z).name() << endl;
44 system(cmd);
45 }
46 };
47
48 template<class NT>
49 class runclassA:public runclass<NT>
50 {
51 public:
52 void print()
53 {
54 cout << x << y << endl;
55 }
56 };
57
58 void main()
59 {
60 runclass<int> *p = new runclassA<int>;
61 p->x = 19;
62 p->y = 12;
63 p->print();
64
65 cin.get();
66 }
67 //-------------------------------------------------------------
68
69 void main()
70 {
71 runclassB<int> X;
72 // 多重继承,父类只能访问自己的虚函数或者纯虚函数
73 // 需要多个父类指针
74 runclass<int> *p = &X;//new runclassB<int>;
75 p->x = 12;
76 p->y = 19;
77 p->print();
78
79 runitclass<int> *p1 = &X;
80 p->cmd = "calc";
81 p1->run();
82
83
84 cin.get();
85 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-06-12 11:01 Dragon-wuxl 阅读(169) 评论(0) 收藏 举报
浙公网安备 33010602011771号