/*
* 类模板对象做函数参数
* 类模板实例化出的对象,向函数传参的方式:
* 1、指定传入的类型——直接显示对象的数据类型(使用比较广泛)
* 2、参数模板化——将对象中的参数变为模板进行传递
* 3、整个类模板化——将这个对象类型模板化进行传递
*/
#include<iostream>
#include<string>
using namespace std;
//类模板
template<class NameType,class AgeType = int>
class Person
{
public:
Person(NameType name, AgeType age)
{
this->m_Age = age;
this->m_Name = name;
}
void showPerson()
{
cout << "name: " << this->m_Name << "age:" << this->m_Age << endl;
}
public:
NameType m_Name;
AgeType m_Age;
};
//1、指定传入的类型
void printPerson1(Person<string, int>& p)
{
p.showPerson();
}
void test23()
{
Person<string, int>p("孙悟空", 100);
printPerson1(p);
}
//2、参数模板化
template<class T1,class T2>
void printPerson2(Person<T1, T2>& p)
{
p.showPerson();
cout << "T1的类型为:" << typeid(T1).name() << endl;
cout << "T2的类型为:" << typeid(T2).name() << endl;
}
void test24()
{
Person<string, int>p("猪八戒", 90);
printPerson2(p);
}
//3、整个类模板化
template<class T>
void printPerson3(T&p)
{
cout << "T的类型为:" << typeid(T).name() << endl;
p.showPerson();
}
void test25()
{
Person<string, int>p("唐僧", 30);
printPerson3(p);
}
int main()
{
test23();
test24();
test25();
cout<<"Hello World!"<<endl;
system("pause");
return 0;
}
C++学习第一百零四篇
最新推荐文章于 2022-01-28 16:51:18 发布