C++ //类模板与继承 //类模板与继承 //注意: //1.当子类继承父类是一个类模板时,子类在声名的时候,要指定出父类中T的类型 //2.如果不指定,编译器无法给子类分配内存 //3.如果想灵活指定出父类中的T的类型,子类也需要变为类模板

 1 #include <iostream>
 2 #include <string>
 3 #include<fstream>
 4 using namespace std;
 5 
 6 
 7 //类模板与继承
 8 template<class T>
 9 class Base
10 {
11 
12     T m;
13 };
14 //class Son :public Base  //错误   ,必须要知道父类中的T的类信号,才能继承给子类
15 class Son:public Base<int>
16 {
17 
18 };
19 
20 void test01()
21 {
22     Son s1;
23 }
24 
25 //2.如果想灵活指定出父类中的T的类型,子类也需要变为类模板
26 template<class T1,class T2>
27 class Son2 :public Base<T2>
28 {
29 public:
30     Son2()
31     {
32         cout << "T1的类型为:" << typeid(T1).name() << endl;
33         cout << "T2的类型为:" << typeid(T2).name() << endl;
34     }
35     T1 obj;
36 };
37 
38 void test02()
39 {
40     Son2<int, char>S2;
41 }
42 
43 
44 int main()
45 {
46     test01();
47     test02();
48 
49     system("pause");
50 
51     return 0;
52 
53 }

 

posted on 2021-08-13 09:37  Bytezero!  阅读(73)  评论(0编辑  收藏  举报