第八章

【8.15】编写一个函数模板,求数组中的最大元素,并调用此函数模板的完整程序。

#include<iostream>
using namespace std;
template <class Type>             
Type max(Type *a)
{ int i,j=0;
      for (i=1;i<3;i++)
	    if (a[i]>a[j])
	    { j=i; } 
      return  a[j];
}
int main()
{ int a1[]={1,2,3};
      double a2[]={1.1,2.2,3.3};
      cout<<max(a1)<<endl;
      cout<<max(a2)<<endl;
	  system("pause");
return 0;
}

【8.17】建立一个用来实现求三个数和的类模板,并调用此类模板的完整程序.

#include<iostream>
using namespace std;
template<typename T>      
class Add_3{                  
  public:
    Add_3(T a,T b,T c)
    { x=a; y=b; z=c;
}
    T sum()
    { return x+y+z;
}
  private:
T x,y,z;
};
int main()
{ Add_3<int> s1(1,2,3);         
  Add_3<double> s2(1.1,2.2,3.3); 
  cout<<"三个整数的和是:"<<s1. sum()<<endl;
  cout<<"三个双精度数的和是:"<<s2.sum()<<endl;
  system("pause");
  return 0;
}

【8.18】将8.17改写成类模板外定义各成员函数

#include<iostream>
using namespace std;
template<typename T>          
class Add_3{                    
  public:
    Add_3(T a,T b,T c);         
    T sum();                
  private:
T x,y,z;
};
template <typename T>         
Add_3<T>::Add_3(T a, T b,T c)     
{ x=a;  y=b;  z=c;
}
template <typename T>         
T Add_3<T>:: sum()             
{ return x+y+z;
}
int main()
{ Add_3<int> s1(3,7,9);         
  Add_3<double> s2(12.34,56.78,67.89); 
  cout<<"三个整数的和是:"<<s1. sum()<<endl;
  cout<<"三个双精度数的和是:"<<s2. sum()<<endl;
  return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值