/*
* 类模板与继承
* 当类模板碰到继承时,需要注意以下几点:
* 1、当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
* 2、如果不指定,编译器无法给子类分配内存
* 3、如果想灵活指定出父类中T的类型,子类也需变为类模板
*/
#include<iostream>
#include<string>
using namespace std;
template<class T>
class Base
{
public:
T m;
};
//class Son: public Base{};//错误,c++编译需要给子类分配内存,必须知道父类中的T的类型才可以向下继承
class Son :public Base<int>//必须指定一个类型
{
};
void test01()
{
Son c;
}
//类模板继续类模板,可以使用T2指定父类中的T类型
template<class T1, class T2>
class Son2 :public Base<T2>
{
public:
Son2()
{
cout << typeid(T1).name() << endl;
cout << typeid(T2).name() << endl;
}
};
void test02()
{
Son2<int, char>child1;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
03-29
481
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-17
3831
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-27
1044
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-17
374
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交