函数模板和类模板
函数模板:
template < class T>
函数
类模板
template < class T>
class 类模板名{
};
#include<iostream>
using namespace std;
template <class T>
class A{
public:
template <class T2>
void Func(T2 t) {
cout << t << endl;
} //成员函数模板
};
int main(){
A<int> a;
a.Func('c'); //成员函数模板Func被实例化
a.Func("hello");
system("pause");
return 0;
}
类模板与函数模板区别
区别:
- 类模板没有自动类型推导的使用方式, 只能用显示指定类型方式
- 类模板在模板参数列表中可以有默认参数
#include <iostream>
#include <string>
using manespace std;
template<class NameType, class AgeType = int>
class Person{
public:
Person(NameType name, AgeType age){
this->mName = name;
this->mAge = age;
}
void showPerson(){
cout << "name: " << this->mName << " age: " << this->mAge << endl;
}
public:
NameType mName;
AgeType mAge;
};
//1、类模板没有自动类型推导的使用方式
void test01()
{
// Person p("孙悟空", 1000); // 错误 类模板使用时候,不可以用自动类型推导
Person <string ,int>p("孙悟空", 1000); //必须使用显示指定类型的方式,使用类模板
p.showPerson();
}
2. 类模板在模板参数列表中可以有默认参数
void test02(){
Person <string> p("猪八戒", 999); //类模板中的模板参数列表 可以指定默认参数
p.showPerson();
}
int main() {
test01();
test02();
system("pause");
return 0;
}
类模板中成员函数创建时机
普通类中的成员函数一开始就可以创建
#include <iostream>
using namespace std;
class Person1{
public:
void showPerson1(){
cout << "Person1 show" << endl;
}
};
class Person2{
public:
void showPerson2(){
cout << "Person2 show" << endl;
}
};
void test() {
//调用方式1
Person1 person1;//实例化对象
person1.showPerson1(); //调用类中的方法
//调用方法2
Person2* person2 = new Person2;
person2->showPerson2();
}
int main() {
test();
system("pause");
return 0;
}
补充:
类模板中的成员函数并不是一开始就创建的,在调用时才去创建
#include <iostream>
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 fun1() {
obj.showPerson1();
}
void fun2() {
obj.showPerson2();
}
};
void test(){
MyClass<Person1> m;
m.fun1();
//m.fun2();//编译会出错,说明函数调用才会去创建成员函数
}
int main() {
test();
system("pause");
return 0;
}