1、类模板
#include<iostream>
using namespace std;
#include<string>
template <class NameType,class AgeType>
class Person
{
public:
Person(NameType name, AgeType age)
{
this->m_Name = name;
this->m_Age = age;
}
NameType m_Name;
AgeType m_Age;
void showPerson()
{
cout << "name:" << this->m_Name << "age:" << this->m_Age << endl;
}
};
void test01()
{
Person<string, int> p1("张三", 20);
p1.showPerson();
}
int main()
{
test01();
system("pause");
return 0;
}
2、类模板和函数模板的区别
#include<iostream>
using namespace std;
#include<string>
template <class NameType,class AgeType=int>
class Person
{
public:
Person(NameType name, AgeType age)
{
this->m_Name = name;
this->m_Age = age;
}
NameType m_Name;
AgeType m_Age;
void showPerson()
{
cout << "name:" << this->m_Name << "age:" << this->m_Age << endl;
}
};
void test01()
{
Person<string, int> p1("张三", 20);
p1.showPerson();
}
void test01()
{
Person<string> p1("张三", 20);
p1.showPerson();
}
int main()
{
test01();
system("pause");
return 0;
}
3、类模板对象做函数参数
#include<iostream>
using namespace std;
#include<string>
template<class T1,class T2>
class Person
{
public:
Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "姓名:" << this->m_Name << "年龄:" << this->m_Age << endl;
}
T1 m_Name;
T2 m_Age;
};
template<class T>
void printPerson3(T&p)
{
p.showPerson();
}
void test03()
{
Person<string, int>p("校长", 40);
printPerson3(p);
}
int main()
{
test03();
system("pause");
return 0;
}
4、类模板与继承
5、类模板成员函数的类外实现
#include<iostream>
using namespace std;
#include<string>
template<class T1,class T2>
class Person
{
public:
Person(T1 name, T2 age);
void showPerson();
T1 m_Name;
T2 m_Age;
};
template<class T1,class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
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", 20);
p.showPerson();
}
int main()
{
test01();
system("pause");
return 0;
}
6、类模板分文件编写
7、类模板与友元