模板
下面是一个针对int的冒泡排序
// _20180301.cpp : Defines the entry point for the console application. // #include "stdafx.h" void Sort(int* arr,int nLength) { int i,k; for (i = 0;i<nLength;i++) { for (k=0;k<nLength-1-i;k++) { if(arr[k]>arr[k+1]) { int temp = arr[k]; arr[k] = arr[k+1]; arr[k+1]=temp; } } } } int main(int argc, char* argv[]) { int arr[] = {1,4,5,2,7,8,3,12,56,879}; Sort(arr,10); return 0; }
如果想要其他任意类型的使用此排序方法呢
此时引出模板
// _20180301.cpp : Defines the entry point for the console application. // #include "stdafx.h" template<class T> void Sort(T* arr,int nLength) { int i,k; for (i = 0;i<nLength;i++) { for (k=0;k<nLength-1-i;k++) { if(arr[k]>arr[k+1]) { T temp = arr[k]; arr[k] = arr[k+1]; arr[k+1]=temp; } } } } int main(int argc, char* argv[]) { int arr[] = {1,4,5,2,7,8,3,12,56,879}; Sort(arr,10); char arr2[] = {'a','b','c','t','m'}; Sort(arr2,5); return 0; }
在函数中使用模板格式
template <class 形参名,class 形参名, ....> 返回类型 函数名(形参列表) { 函数体 }
自定义类型使用模板
// _20180301.cpp : Defines the entry point for the console application. // #include "stdafx.h" class Base { public: Base(int x,int y) :x(x),y(y) { } bool operator>(const Base& base) { return this->x > base.x && this->y > base.y; } private: int x; int y; }; template<class T> void Sort(T* arr,int nLength) { int i,k; for (i = 0;i<nLength;i++) { for (k=0;k<nLength-1-i;k++) { if(arr[k]>arr[k+1]) { T temp = arr[k]; arr[k] = arr[k+1]; arr[k+1]=temp; } } } } int main(int argc, char* argv[]) { int arr[] = {1,4,5,2,7,8,3,12,56,879}; Sort(arr,10); char arr2[] = {'a','b','c','t','m'}; Sort(arr2,5); Base b1(1,1),b2(4,4),b3(6,6),b4(2,2),b5(8,8); Base arr3[]={b1,b2,b3,b4,b5}; Sort(arr3,5); return 0; }
在架构提、类中使用模板
类模板的格式为:
template<class 形参名,class 形参名,...> class 类名 { }
例子:
// _20180301.cpp : Defines the entry point for the console application. // #include "stdafx.h" template<class T,class M> class Base { private: T x; T y; M a; M b; public: Base(T tx,T ty,M ma,M mb) :x(tx),y(ty),a(ma),b(mb) { } T max() { if (x>y) return x; else return y; } M min() { if(a<b) return a; else return b; } }; int main(int argc, char* argv[]) { Base<int,char> base(1,2,'a','z'); int max = base.max(); char min = base.min(); return 0; }
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论