简单的案例

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. template<class NameType,class AgeType>
  5. class People{
  6. public:
  7. string name;
  8. int age;
  9. People(NameType name,AgeType age){
  10. this->name = name;
  11. this->age = age;
  12. }
  13. void show(){
  14. cout << "姓名:" + name << ",年龄:" << age << endl;
  15. }
  16. };
  17. int main()
  18. {
  19. People<string,int> p("小明",12);//类模板在调用时必须声明类型
  20. p.show();
  21. return 0;
  22. }

类模板和函数模板的区别

  • 类模板不支持类型推导,估计在调用时必须声明类型(除非设置了默认参数)
  • 类模板在模板参数表中可以有默认参数

设置类模板的默认数据类型

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. template<class NameType = string,class AgeType = int>//设置默认类型
  5. class People{
  6. public:
  7. string name;
  8. int age;
  9. People(NameType name,AgeType age){
  10. this->name = name;
  11. this->age = age;
  12. }
  13. void show(){
  14. cout << "姓名:" + name << ",年龄:" << age << endl;
  15. }
  16. };
  17. int main()
  18. {
  19. People<> p("小明",12);//在设置默认类型的情况下可以不声明,但<>还是要保留
  20. p.show();
  21. return 0;
  22. }