问题及代码:
原代码:
#include<iostream>
using namespace std;
//定义函数模板
template<class T>
T max(T a, T b)
{
return (a>b)?a:b;
}
int main()
{
int x=2,y=6;
double x1=9.123,y1=12.6543;
cout<<"把T实例化为int:"<<max(x,y)<<endl;
cout<<"把T实例化为double:"<<max(x1,y1)<<endl;
return 0;
}
解决方案:
/*
*Copyright (c) 2015,烟台大学计算机学院
*All rights reserved.
*文件名称:test.cpp
*作者:孙金艺
*完成日期:2015年06月27日
*版本号:v1.0
*
*问题描述:分析下面程序出现的编译错误,给出解决的方案。
*输入描述:
*程序输出:
*/
#include<iostream>
using namespace std;
//定义函数模板
template<class T>
T lmax(T a, T b)
{
return (a>b)?a:b;
}
int main()
{
int x=2,y=6;
double x1=9.123,y1=12.6543;
cout<<"把T实例化为int:"<<lmax(x,y)<<endl;
cout<<"把T实例化为double:"<<lmax(x1,y1)<<endl;
return 0;
}
运行结果:
知识点总结:出现问题的原因是名字冲突,将冲突的函数名max改本地名为lmax,就可以了
学习心得:加油!