五. 模板函数实现原理剖析
六. 类模板基本语法
#include <iostream> using namespace std; template<class T> class Person{ public: Person(T id ,T age){ this->mId = id; this->mAge = age; } void Show(){ cout<<"ID:"<<mId<<" Age:"<<mAge<<endl; } private: T mId; T mAge; }; void test1(){ //函数模板在调用的时候,可以自动类型推导 //类模板必须显式指定类型 Person<int> p(10,20); p.Show(); } int main() { test1(); return 0; }
七. 函数模板案例_char和int类型组数排序
#include <iostream> using namespace std; //对char类型和int类型数组进行排序 template<class T> void PrintArray(T* arr, int len){ for(int i = 0; i<len;i++){ cout<<arr[i]<<" "; } cout<<endl; } //从大到小排序 template<class T> void MySort(T * arr, int len){ for(int i = 0; i<len;i++){ for(int j=i+1; j<len;j++){ if(arr[i]<arr[j]){ T temp = arr[i]; arr[i] = arr[j]; arr[j] =temp; } } } } int main() { //数组 int arr[] = {2,6,1,8,9,2}; //数组长度 int len = sizeof(arr)/sizeof(int); cout<<"Before sorting"<<endl; PrintArray(arr,len); MySort(arr,len); cout<<"After sorting"<<endl; PrintArray(arr,len); cout<<"----------------------------"<<endl; char arr2[] = {'f','u','k','b','s','m'}; int len2 = sizeof(arr2)/sizeof(char); cout<<"Before sorting"<<endl; PrintArray(arr2,len2); MySort(arr2,len2); cout<<"After sorting"<<endl; PrintArray(arr2,len2); return 0; }
运行结果:
Before sorting 2 6 1 8 9 2 After sorting 9 8 6 2 2 1 ---------------------------- Before sorting f u k b s m After sorting u s m k f b
八. 类模板派生普通类
//类模板派生普通类 #include <iostream> using namespace std; template<class T> class Person{ public: Person(){ this->mAge=0; } private: T mAge; }; //为什么? //类区定义对象,这个对象是不是需要编译分配内存 class SubPerson : public Person<int>{ }; int main() { return 0; }
#include <iostream> using namespace std; template<class T> class Animal { public: void makeSound(){ cout<< mAge<< "岁动物在叫!"<<endl; } public: T mAge; }; template<class T> class Cat: public Animal<T> { public: void makeSound(){ cout<< mAge<< "岁猫在叫!"<<endl; } public: T mAge; }; int main() { Cat <int>cat; cat.makeSound(); return 0; }