鱼C论坛

 找回密码
 立即注册
查看: 981|回复: 0

[技术交流] C++旅程第10站——类模板1

[复制链接]
发表于 2020-5-28 22:05:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Knowledge speaks,but wisdom listens.         —— Jimi Hendrix
                                                                                       类模板
类模板作用:
  建立一个通用的类,类中的成员、数据类型可以不具体制定,用一个虚拟的类型来代表

语法:
  1. template<typename T>
复制代码

template——声明创建模板
typename——表明其后面的符号是一种数据类型,可以用class代替
T——通用的数据类型,名称可以替换,通常为大写字母
  1. #include<iostream>
  2. #include<string>

  3. using namespace std;

  4. //类模板
  5. template<class Nametype ,class Agetype>
  6. class Animal
  7. {
  8. public:
  9.         Animal(Nametype name,Agetype age)
  10.         {
  11.                 this->m_name = name;
  12.                 this->m_age = age;
  13.         }        
  14.         
  15.         void show()
  16.         {
  17.                 cout << "name : " << this->m_name << endl;
  18.                 cout << "age : " << this->m_age << endl;
  19.         }
  20.         
  21.         Nametype m_name;
  22.         Agetype m_age;
  23. };

  24. void test1()
  25. {
  26.         //指定Nametype->string  Agetype->int
  27.         Animal<string,int> p1("猫咪",11);
  28.         p1.show();
  29. }

  30. int main()
  31. {
  32.         test1();
  33.         
  34.         
  35.         return 0;
  36. }
复制代码

类模板与函数模板区别有两点:
1、类模板没有自动类型推导的使用方式
2、类模板在模板参数列表中可以有默认参数
  1. #include<iostream>
  2. #include<string>

  3. using namespace std;

  4. //类模板
  5. template<class Nametype ,class Agetype = int>
  6. class Animal
  7. {
  8. public:
  9.         Animal(Nametype name,Agetype age)
  10.         {
  11.                 this->m_name = name;
  12.                 this->m_age = age;
  13.         }        
  14.         
  15.         void show()
  16.         {
  17.                 cout << "name : " << this->m_name << endl;
  18.                 cout << "age : " << this->m_age << endl;
  19.         }
  20.         
  21.         Nametype m_name;
  22.         Agetype m_age;
  23. };

  24. void test1()
  25. {
  26.         //指定Nametype->string  Agetype->int
  27.         Animal <string,int> p1("猫咪",11);// 对   必须使用显示指定类型的方式,使用类模板
  28.         Animal p("小猪仔",10);//错   类模板使用的时候不可以用自动类型推导
  29.         
  30.         p1.show();
  31.          
  32.         Animal <string> p2("羊驼",9);//类模板中的模板参数列表,可以指定默认参数
  33.         p2.show();
  34. }

  35. int main()
  36. {
  37.         test1();
  38.         
  39.         
  40.         return 0;
  41. }
复制代码

                                               渣渣加油中.................................

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-27 21:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表