1、类模板与函数模板区别主要有两点:
- 类模板没有自动类型推导的使用方式
- 类模板在模板参数列表中可以有默认参数
#include<iostream>
#include<string>
using namespace std;
template<class NameType , class AgeType = int >//可以有默认参数,如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
class Person
{
public:
Person(NameType name, AgeType age)
{
this->m_name = name;
this->m_age = age;
}
void Show()
{
cout << "名字:" << this->m_name << endl;
cout << "年龄:" << this->m_age << endl;
}
NameType m_name;
AgeType m_age;
};
int main()
{
//Person p("李四",100); 错误 类模板使用时候,不可以用自动类型推导
Person<string, int>p("张三", 18);//必须使用显示指定类型的方式,使用类模板
p.Show();
Person<string>p("王五", 18);//类模板中的模板参数列表 可以指定默认参数
return 0;
}
2、类模板中的成员函数调用时机
类模板中成员函数和普通类中成员函数创建时机是有区别的:
- 普通类中的成员函数一开始就可以创建
- 类模板中的成员函数在调用时才创建
#include<iostream>
#include<string>
using namespace std;
class Person1
{
public:
void ShowPerson1()
{
cout << "调用person1" << endl;
}
};
class Person2
{
public:
void ShowPerson2()
{
cout << "调用person2" << endl;
}
};
template<class T>
class myclass
{
public:
T obj;
//类模板中的成员函数并不是一开始就创建的,在调用时才去创建
void display1()
{
obj.ShowPerson1();
}
void display2()
{
obj.ShowPerson2();
}
};
int main()
{
myclass<Person1> m;
m.display1();
//m.display2();//编译出错,说明程序编译运行的时候才会去创建类模板中的函数
return 0;
}