4.1 写法template <T…> 紧跟着是类
4.2 与函数模板区别,可以有默认类型参数
4.3 函数模板可以进行自动类型推导,而类模板不可以
4.4 类模板中的成员函数 一开始不会创建出来,而是在运行时才去创建
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
//类模板
template<class T1,class T2=int>//类模板可以有默认类型
class Mentor {
public:
Mentor(T1 name, T2 age) {
this->m_age = age;
this->m_name = name;
}
void showMentor() {
cout << "姓名是:" << this->m_name << " 年龄是:" << this->m_age << endl;
}
T1 m_name;
T2 m_age;
};
void test01() {
//自动类型推导 ,类模板 不支持
//Mentor m("锯嘴葫芦", 19);//C2955 'Mentor': use of class template requires template argument list
//显示指定类型
Mentor<string,int> mentor("渣渣猫",25);
mentor.showMentor();
Mentor<string> mentor1("土拨鼠", 26);
mentor1.showMentor();
}
int main(){
test01();
system("pause");
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
#if(1)
class Nick {
public:
void showNick() {
cout << "showNick()调用..." << endl;
}
};
class Judy {
public:
void showJudy() {
cout << "showJudy()调用..." << endl;
}
};
template<class T>
class Gourd {
public:
T obj;
void func1() {
obj.showNick();
}
void func2() {
obj.showJudy();
}
};
void test01() {
Gourd<Nick> gourd;
gourd.func1();
//gourd.func2();//C2039 'showJudy': is not a member of 'Nick'
}
int main(){
test01();
system("pause");
return 0;
}
#endif