c++中的template的用法?

bjxbt 2001-11-16 03:12:36
# include "iostream.h"

template <class t>
T max(T x,T y)
{ return ((x>y)?x:y);}

void main()
{ int a=1;
double b=2;
cout<<max<int>(a,b);
}

书上讲对模版的实例化是正确的,但在bc下编译错误
...全文
642 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
TyraelTiger 2001-11-16
  • 打赏
  • 举报
回复
同意楼上的楼上的意见
TyraelTiger 2001-11-16
  • 打赏
  • 举报
回复
同意楼上的楼上的意见
huanshilang 2001-11-16
  • 打赏
  • 举报
回复
楼上说的好
stevenW 2001-11-16
  • 打赏
  • 举报
回复
既然定义了template <class t>
T max(T x,T y)
{ return ((x>y)?x:y);}
,那么在使用该template时就要求保证x,y是同一类型T的变量,正如MSDN里所言,这是template的一个优点,它保证了进行比较的变量的类型相同。想一下,比较猪和狗怎么比较?客观上,我们可以比较猪肉和狗肉哪个味道好!
injune 2001-11-16
  • 打赏
  • 举报
回复
上面的在turbo c++ 3.0 上面通过:
下面的在vc6 下通过.
# include "iostream.h"

template <class T>
T max(T x,T y)
{
return ((x>y)?x:y);
}


void main()
{
double a=1;
double b=2;
double max(double,double);
cout <<max(a,b);
}

kingfish 2001-11-16
  • 打赏
  • 举报
回复
VC下只要改下面就行:
template <class t>

template <class T>
injune 2001-11-16
  • 打赏
  • 举报
回复
改写成:
# include "iostream.h"
template <class T>
T max(T x,T y)
{ return ((x>y)?x:y);}

double max(double,double);
void main()
{ int a=1;
double b=2;
cout<<max(a,b);
}
一切ok了.
lanying 2001-11-16
  • 打赏
  • 举报
回复
gzz
bjxbt 2001-11-16
  • 打赏
  • 举报
回复
cout<<max<int>(a,b);编译认为此句error
bjxbt 2001-11-16
  • 打赏
  • 举报
回复
cout<<max<int>(a,b); 编译认为此句error
bjxbt 2001-11-16
  • 打赏
  • 举报
回复
# include "iostream.h"
template <class T>
T max(T x,T y)
{ return ((x>y)?x:y);}

double max(double,double);
void main()
{ int a=1;
double b=2;
cout<<max<int>(a,b);
}

编译不能通过
kingfish 2001-11-16
  • 打赏
  • 举报
回复
template <class t>

template <class T>
dis_covery 2001-11-16
  • 打赏
  • 举报
回复

# include "iostream.h"
template <class t>
T max(T x,T y)
{ return ((x>y)?x:y);}

double max(double,double);
void main()
{ int a=1;
double b=2;
cout<<max<int>(a,b);
}

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧