15第十六项目三——max带来的冲突

来源:互联网 发布:手机制作结婚照软件 编辑:程序博客网 时间:2024/04/30 09:00
/*
 * Copyright (c) 2014, 烟台大学计算机学院
 * All rights reserved.
 * 文件名称:test.cpp
 * 作    者:李晓凯
 * 完成日期:2015年 6 月 21 日
 * 版 本 号:v1.0
 *

 * 问题描述:分析下面程序出现的编译错误,给出解决的方案。

* 输入描述:

 * 程序输出:

 */

异常程序:

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

解决方案一、

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


解决方案二、

在方案一的基础上再在前面加上std,明确指出是调用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;}

解决方案三、

去掉using namespace std,然后在cout和endl前加上“std::”就可以了。

#include<iostream>//定义函数模板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;    std::cout<<"把T实例化为int:"<<max(x,y)<<std::endl;    std::cout<<"把T实例化为double:"<<max(x1,y1)<<std::endl;    return 0;}



0 0
原创粉丝点击