第16周上机实践项目3——max带来的冲突

来源:互联网 发布:手机制作结婚照软件 编辑:程序博客网 时间:2024/04/30 11:45

分析下面程序出现的编译错误,给出解决的方案。

#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;}

其实C++中有了一个标准的max函数,经过一年多的学习也知道了这一点,每次打出max的时候,codeblocks就会给出补充,这明显是已经定义过了的,所以解决方法有一下几种

1、在max前加std::,代表使用标准库中的max

#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:"<<std::max(x,y)<<endl;    cout<<"把T实例化为double:"<<std::max(x1,y1)<<endl;    return 0;}

2、在max前加::,代表使用当前定义的max

#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;}

3、把using namespace std改成using std::cout;using std::endl,代表只使用标准库中的cout和endl

#include<iostream>using std::cout;using std::endl;//定义函数模板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;}
0 0
原创粉丝点击