2.2.1类模板语法
作用:通过建立一个通用的类,类中的成员 数据类型可以不具体指定,用一个虚拟的类型代表。
语法:template <typename T>
类
#include<iostream>
#include<string>
using namespace std;
template<class NameType, class AgeType>
class Person
{
public:
Person (NameType name, AgeType age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "name:" << this->m_Name << "age:" << this->m_Age;
}
NameType m_Name;
AgeType m_Age;
};
void test01()
{
Person<string, int> p1("孙悟空",999);
p1.showPerson();
}
int main()
{
test01();
return 0;
}
2.2.2类模板与函数模板
两者区别:
- 类模板没有自动类型推导的使用方式
- 类模板在模板参数列中可以有默认参数
#include<iostream>
#include<string>
using namespace std;
template<class NameType, class AgeType=int> //默认int
class Person
{
public:
Person (NameType name, AgeType age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "name:" << this->m_Name << "age:" << this->m_Age;
}
NameType m_Name;
AgeType m_Age;
};
//类模板无自动类型推导
void test01()
{
//Person("孙悟空",1000); 错误,无法自动类型推导
Person<string, int> p1("孙悟空",999);
p1.showPerson();
}
//类模板在模板参数列表中可以有默认参数
void test02()
{
Person<string> p2("猪八戒", 999);
p2.showPerson();
}
int main()
{
test01();
test02();
return 0;
}
2.2.3类模板中成员函数创建时机
类模板和普通函数中成员函数创建时机不同:
- 普通类中的成员函数一开始就可以创建
- 类模板中的成员函数在调用时才创建
#include<iostream>
#include<string>
using namespace std;
class Person1
{
public:
void showPerson1()
{
cout << "Person1 show" << endl;
}
};
class Person2
{
public:
void showPerson2()
{
cout << "Person2 show" << endl;
}
};
template<class T>
class MyClass
{
public:
T obj;
//类模板中的成员函数,并不是一开始就创建,而是在模板调用时再生成
void func1()
{
obj.showPerson1();
}
void func2()
{
obj.showPerson2();
}
};
void test01()
{
MyClass <Person1> m;
m.func1();
//m.func2();编译时会出错,说明函数调用才会去创建成员函数
}
int main()
{
test01();
return 0;
}