类模板的定义
定义一个类:
#include <iostream>
#include <string>
class Student {
public:
Student(string name, int age) {
this->name = name;
this->age = age;
}
private:
NameType name;
AgeType age;
};
void main() {
Student student1 = {"xiaoming",12};
}
在此基础上,进行修改,定义类模板:
#include <iostream>
#include <string>
template<class NameType, class AgeType>
class Student {
public:
Student(NameType name, AgeType age) {
this->name = name;
this->age = age;
}
private:
NameType name;
AgeType age;
};
void main() {
//使用类模板初始化的时候必须显示指明数据类型
Student<std::string, int> student1 = {"xiaoming",12};
}
类模板初始化的时候必须显示指明数据类型
需要注意:使用类模板初始化的时候必须显示指明数据类型(这与函数模板不同)
如果不指定,会报错,如下图:
类模板可以具有默认数据类型
#include <iostream>
#include <string>
//指定AgeType的数据类型为int
template<class NameType, class AgeType = int>
class Student {
public:
Student(NameType name, AgeType age) {
this->name = name;
this->age = age;
}
private:
NameType name;
AgeType age;
};
void main() {
//此处可以不指定AgeType的数据类型
Student<std::string> student1 = {"xiaoming",12};
//也可以指定AgeType为其他数据类型
Student<std::string, double> student2 = {"lihua",15};
}
需要注意的是:
如果第二个参数有默认类型,那么后面所有的参数都要有默认类型,否则会报错;
所以需要把有默认类型的参数都放到后面。