|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Knowledge speaks,but wisdom listens. —— Jimi Hendrix
类模板
类模板作用:
建立一个通用的类,类中的成员、数据类型可以不具体制定,用一个虚拟的类型来代表
语法:
template——声明创建模板
typename——表明其后面的符号是一种数据类型,可以用class代替
T——通用的数据类型,名称可以替换,通常为大写字母
- #include<iostream>
- #include<string>
- using namespace std;
- //类模板
- template<class Nametype ,class Agetype>
- class Animal
- {
- public:
- Animal(Nametype name,Agetype age)
- {
- this->m_name = name;
- this->m_age = age;
- }
-
- void show()
- {
- cout << "name : " << this->m_name << endl;
- cout << "age : " << this->m_age << endl;
- }
-
- Nametype m_name;
- Agetype m_age;
- };
- void test1()
- {
- //指定Nametype->string Agetype->int
- Animal<string,int> p1("猫咪",11);
- p1.show();
- }
- int main()
- {
- test1();
-
-
- return 0;
- }
复制代码
类模板与函数模板区别有两点:
1、类模板没有自动类型推导的使用方式
2、类模板在模板参数列表中可以有默认参数
- #include<iostream>
- #include<string>
- using namespace std;
- //类模板
- template<class Nametype ,class Agetype = int>
- class Animal
- {
- public:
- Animal(Nametype name,Agetype age)
- {
- this->m_name = name;
- this->m_age = age;
- }
-
- void show()
- {
- cout << "name : " << this->m_name << endl;
- cout << "age : " << this->m_age << endl;
- }
-
- Nametype m_name;
- Agetype m_age;
- };
- void test1()
- {
- //指定Nametype->string Agetype->int
- Animal <string,int> p1("猫咪",11);// 对 必须使用显示指定类型的方式,使用类模板
- Animal p("小猪仔",10);//错 类模板使用的时候不可以用自动类型推导
-
- p1.show();
-
- Animal <string> p2("羊驼",9);//类模板中的模板参数列表,可以指定默认参数
- p2.show();
- }
- int main()
- {
- test1();
-
-
- return 0;
- }
复制代码
渣渣加油中.................................
|
|