目录
学习目标
- 类模板实例化出的对象,向函数传参的方式
三种传入方式
1.指定传入类型——直接显示对象的数据类型
#include<iostream>
using namespace std;
#include<string>
//类模板
template<class NameType,class AgeType>
class Person {
public:
Person(NameType name,AgeType age) {
this->m_age=age;
this->m_name=name;
}
void showPerson() {
cout<<"姓名:"<<this->m_name<<"年龄:"<<this->m_age<<endl;
}
public:
NameType m_name;
AgeType m_age;
};
//1.指定传入的类型
void printPerson(Person<string,int> &p)
{
p.showPerson();
}
void test01()
{
Person<string,int>p("孙悟空",100);
printPerson(p);
}
int main()
{
test01();
system("pause");
return 0;
}
2. 参数模板化
#include<iostream>
using namespace std;
#include<string>
#include<typeinfo>
//类模板
template<class NameType,class AgeType>
class Person {
public:
Person(NameType name,AgeType age) {
this->m_age=age;
this->m_name=name;
}
void showPerson() {
cout<<"姓名:"<<this->m_name<<"年龄:"<<this->m_age<<endl;
}
public:
NameType m_name;
AgeType m_age;
};
//2.参数模板化
template<class T1,class T2>
void printPerson02(Person<T1,T2> &p)
{
p.showPerson();
//cout<<"T1的类型为:"<<typeid(T1).name()<<endl;
//cout<<"T2的类型为:"<<typeid(T2).name()<<endl;
}
void test02()
{
Person<string,int>p("猪八戒",90);
printPerson02(p);
}
int main()
{
test02();
system("pause");
return 0;
}
3.整个类模板化
#include<iostream>
using namespace std;
#include<string>
#include<typeinfo>
//类模板
template<class NameType,class AgeType>
class Person {
public:
Person(NameType name,AgeType age) {
this->m_age=age;
this->m_name=name;
}
void showPerson() {
cout<<"姓名:"<<this->m_name<<"年龄:"<<this->m_age<<endl;
}
public:
NameType m_name;
AgeType m_age;
};
//3.整个类模板化
template<typename T1>
void printPerson3(T1 &p)
{
p.showPerson();
}
void test03()
{
Person<string,int>p("唐僧",30);
printPerson3(p);
}
int main()
{
test03();
system("pause");
return 0;
}
总结
- 通过类模板创建的对象,可以有三种方式向函数进行传参
- 使用比较广泛的是第一种:指定传入的类型