1.基础语法
#include<iostream>
using namespace std ;
#include<string>
//类模板写法
//类模板应用在一个类中,可以暂时不确定类中成员具体的数据类型。
template<class nametype,class agetype>
class Person{
public:
Person(nametype name,agetype age){
this->m_age = age;
this->m_name = name;
}
nametype m_name;
agetype m_age;
void showperson(){
cout<<"姓名:"<<this->m_name<<endl;
cout<<"年龄:"<<this->m_age<<endl;
}
void showbifen(){
cout<<"红队:"<<this->m_name<<" "<<"蓝队:"<<this->m_age<<endl;
}
};
void test01(){
Person<string,int>p1("8号程序员",20);//类模板的调用,<>内指定具体的数据类型。
Person<int,int>p2(85,88); //两种不同方式的调用。
p1.showperson();
p2.showbifen();
}
int main () {
test01();
system("pause");
return 0;
}
2.类模板与模板函数区别
#include<iostream>
using namespace std ;
#include<string>
template<class nametype = string,class agetype = int> //设置默认数据类型。
class Person{
public:
Person(nametype name,agetype age ){
this->m_age = age;
this->m_name = name;
}
nametype m_name;
agetype m_age;
void showperson(){
cout<<"姓名:"<<this->m_name<<endl;
cout<<"年龄:"<<this->m_age<<endl;
}
};
void test01(){
//Person p1("8号程序员",22); //未指定类模板的具体数据类型。
Person <string>p2("八号程序员",22); //当未指定具体数据类型但提供默认数据类型时,走默认数据类型。
Person<> p3("八号程序员",22); //哪怕所有变量均可走默认数据类型,<>不能省略。
}
int main () {
system("pause");
return 0;
}
3.类模板中成员函数创建时机
#include<iostream>
using namespace std ;
#include<string>
class Hanshu{
public:
static void func01(){
cout<<"普通类中函数的调用"<<endl;
}
};
template<class nametype = string,class agetype = int> //设置默认数据类型。
class Person{
public:
Person(nametype name,agetype age ){
this->m_age = age;
this->m_name = name;
}
nametype m_name;
agetype m_age;
void showperson(){
cout<<"姓名:"<<this->m_name<<endl;
cout<<"年龄:"<<this->m_age<<endl;
}
static void func02(){
cout<<"模板类中函数的调用"<<endl;
}
};
void test01(){
Hanshu::func01();//普通类中可正常调用该成员函数
//Person::func02();//类模板下在未创建对象时不可调用(此时并未创建)。
Person<> p1("八号程序员",22);
p1.func02();//此时可通过实例化对象后(即模板被调用后)成员函数才被创建。。
}
int main () {
test01();
system("pause");
return 0;
}
4.类模板对象做函数参数
*#include<iostream>
using namespace std ;
#include<string>
template<class nametype ,class agetype > //设置默认数据类型。
class Person{
public:
Person(nametype name,agetype age ){
this->m_age = age;
this->m_name = name;
}
nametype m_name;
agetype m_age;
void showperson(){
cout<<"姓名:"<<this->m_name<<endl;
cout<<"年龄:"<<this->m_age<<endl;
}
};
//方式一:
void test01(Person<string,int>& p){
p.showperson();
}
//方式二:
template<class T1,class T2>
void test02(Person<T1,T2>& p){
p.showperson();
}
//方式三:
template<class T>
void test03(T& p){
p.showperson();
}
int main () {
Person<string,int> p("八号程序员",22);
test01(p);
test02(p);
test03(p);
system("pause");
return 0;
}
本文是根据B站内容:《黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难》https://www.bilibili.com/video/BV1et411b73Z?p=314 学习整理笔记。