c++中的函数模板

#include<iostream>template<classT>TMAX(T*P);intmain(){usingnamespacestd;intsh[5];inti... #include<iostream>
template<class T>
T MAX(T *P);

int main()
{using namespace std;
int sh[5];
int i=0;
double ch[5];
cout<<"enter 5 int num"<<endl;
for( i=0;i<5;i++)
cin>>sh[i];
T max=MAX(sh);
cout<<max;
cout<<"enter 5 double num"<<endl;
for( i=0;i<5;i++)
cin>>ch[i];
T max=MAX(ch);
cout<<max;
return 0;
}
template <class T>
T MAX(T *P)
{T tem;
for(int i=0;i<5;i++)
if(tem<p[i])
tem=p[i];
return tem;
}
展开
 我来答
Eli2021
2011-09-29 · TA获得超过664个赞
知道小有建树答主
回答量:1266
采纳率:72%
帮助的人:394万
展开全部
//以下是正确程序,自己找自己错在哪里

#include <iostream>

using namespace std;

template<class T>
T MAX(T *P);

int main()
{
int sh[5];
int i=0;
double ch[5];
cout<<"enter 5 int num"<<endl;
for( i=0; i<5; i++)
cin>>sh[i];
int max=MAX(sh);
cout<<max<<endl;
cout<<"enter 5 double num"<<endl;
for( i=0; i<5; i++)
cin>>ch[i];
double max2=MAX(ch);
cout<<max2<<endl;
return 0;
}

template <class T>
T MAX(T *p)
{
T tem = p[0];
for(int i=1; i<5; i++)
if(tem<p[i])
tem=p[i];
return tem;
}
更多追问追答
追问
也就是说主函数里面不能用T来定义变量。但是你这个程序好想还有问题啊
追答
我用g++可以编译运行是正确的,你说有什么问题?
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式