c++函数模板的使用

xiaoxiao2021-02-28  109

#include <iostream>//函数模板的使用 //#define max(a,b)((a) > (b)?(a):(b))宏定义 using namespace std; template<class type> type max(type a,type b) //整形数和实型数进行比较 {  return (a > b) ? a : b; } char *max(char * a, char *b) //字符串的模板 {  if (strcmp(a, b))   return a;  else   return b; } void main() {  double a, b;  cin >> a >> b;  cout << max(a, b) << endl; } //Example 2 template <class type,int len>//定义一个模板类型 type Max(type array[len]) //定义函数模板 {  type ret = array[0];//定义一个变量  for (int i = 1; i < len; i++) //遍历数组元素  {   ret = (ret > array[i]) ? ret : array[i];//比较数组元素的大小  }  return ret;//返回最大值 } void main() {  int array[5] = {1,2,3,4,5};// 定义一个整型数组  int iret = Max<int, 5>(array);//调用函数模板Max  double dset[3] = {10.5,11.2,9.8};//定义实数数组  double dret = Max<double, 3>(dset);//调用函数模板Max  cout << dret << endl; }
转载请注明原文地址: https://www.6miu.com/read-48611.html

最新回复(0)