2.2.4类模板对象做函数参数
类模板实例出的对象,向函数传参的方式有三种:
- 指定传入的类型—-直接显示对象的数据类型
- 参数模板化—-—将对象中的参数变为模板进行传递
- 整个类模板化——将这个对象模型模板化进行传递
#include<iostream>
#include<string>
using namespace std;
//类模板对象做函参数
template<class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age)
{
this->m_Age = age;
this->m_Name = name;
}
void showPerson()
{
cout << "姓名:" << this->m_Name << "年龄:" << this->m_Age << endl;
}
T1 m_Name;
T2 m_Age;
};
//1.传入指定类型 最常用
void printPerson1(Person<string,int>&p)
{
p.showPerson();
}
void test01()
{
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 test02()
{
Person<string, int>p("猪八戒", 90);
printPerson2(p);
}
//3.整个类模板化
template<class T>
void printPerson3(T &p)
{
p.showPerson();
cout << "T的类型为:" << typeid(T).name() << endl;
}
void test03()
{
Person<string, int>p("唐僧", 30);
printPerson3(p);
}
int main()
{
/*test01();
test02();*/
test03();
return 0;
}
2.2.5类模板与继承
当类模板碰到继承时,需注意:
- 当子类继承父类是一个模板时,子类在声明的时候,要指定出父类中T的类型
- 如果不指定,编译器无法给子类分配内存
- 如果想灵活的指出父类中T的类型,子类也需要变为模板
#include<iostream>
#include<string>
using namespace std;
template<class T>
class Base
{
public:
T m;
};
//class Son:public Base //错误 ,必须要知道父类中T的类型,才能继承给子类
class Son :public Base<int>
{
};
void test01()
{
Son s1;
}
//如果想灵活的指定父类中T的类型,子类也需要变为类模拟板
template<class T1,class T2>
class Son2:public Base<T2>
{
public:
T1 obj;
Son2()
{
cout << "T1的类型为:" << typeid(T1).name() << endl;
cout << "T2的类型为:" << typeid(T2).name() << endl;
}
};
void test02()
{
Son2<int ,char> s2; //类模板中的对象要用显示指定类型
}
int main()
{
test01();
test02();
return 0;
}
2.2.6类模板成员函数在类外实现
#include<iostream>
#include<string>
using namespace std;
template<class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age);
/*{
this->m_Age = age;
this->m_Name = name;
}*/
void showPerson();
/*{
cout << "姓名:" << this->m_Name << "年龄:" << this->m_Age << endl;
}
*/
T1 m_Name;
T2 m_Age;
};
//构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->m_Age = age;
this->m_Name = name;
}
template<class T1, class T2>
void Person<T1, T2>::showPerson()
{
cout << "姓名:" << this->m_Name << "年龄:" << this->m_Age << endl;
}
void test01()
{
Person<string, int> p("Tom", 100);
p.showPerson();
}
int main()
{
test01();
return 0;
}