1、类模板语法
类模板作用:建立一个通用类,类中的成员 数据类型可以不具体制定,用一个虚拟的类型来代表
template<typename T>
类
解释:
template :声明创建模板
typename :表明其后面是一种数据类型,可以用class代替
T:通用的数据类型,名称可以替换,通常大写字母
//类模板
template<class NameT, class AgeT>
class person
{
public:
NameT m_name;
AgeT m_age;
person(NameT name, AgeT age)
{
this->m_name = name;
this->m_age = age;
}
void show()
{
cout << this->m_name << " " << this->m_age << endl;
}
};
void test01()
{
person<string, int> p1("孙悟空", 200);
p1.show();
}
int main()
{
test01();
system("pause");
return 0;
}
2、类模板和函数模板的区别
- 类模板没有自动类型推导的使用方式
- 类模板在模板参数列表中可以有默认参数
//类模板
template<class NameT, class AgeT = int>//参数列表中可以有默认参数
class person
{
public:
NameT m_name;
AgeT m_age;
person(NameT name, AgeT age)
{
this->m_name = name;
this->m_age = age;
}
void show()
{
cout << this->m_name << " " << this->m_age << endl;
}
};
void test01()
{
//person p2("liuzgiu", 20);//报错,无法使用自动类型推导
person<string, int> p1("孙悟空", 200);
p1.show();
}
void test02()
{
}
int main()
{
test01();
system("pause");
return 0;
}
3、类模板中成员函数创建时机
- 普通类中的成员函数一开始就可以创建
- 类模板中的成员函数在调用时才创建
class person2
{
public:
void showPerson2()
{
cout << "person2 show" << endl;
}
};
class person3
{
public:
void showPerson3()
{
cout << "person3 show" << endl;
}
};
//类模板
template<class T>//参数列表中可以有默认参数
class person1
{
public:
T obj;
void func1()
{
obj.showPerson2();
}
void func2()
{
obj.showPerson3();
}
};
void test01()
{
person1<person2>m;
m.func1();
}
int main()
{
test01();
system("pause");
return 0;
}
总结:类模板中的成员函数并不是 一开始就创建的,而是在调用的时候才创建
4、类模板对象做函数参数
学习目标:类模板实例化出的对象,向函数传参的方式
三种传参方式:
- 指定传入的类型:直接显示对象的数据类型
- 参数模板化:将对象中的参数变为模板进行传递
- 整个类模板化:将这个对象类型模板化进行传递