您的位置:首页 > 编程语言 > C语言/C++

C++模板函数的小问题解决

2015-08-07 23:19 267 查看
#include<iostream>
#include<string>
using namespace std;
template<class Type>
Type min(Type a,Type b)
{
if(a<b)
return a;
else
return b;

}
char *min(char *a, char *b)
{
if(strcmp(a,b))
return b;
else
return a;
}

int main()
{

cout<<"The minimum value is "<<min(10,1)<<endl;
cout<<"The minimum value is "<<min('a','b')<<endl;
cout<<"The minimum value is "<<min("hi","mr")<<endl;

}


最近在学习C++程序设计,遇到了个小问题,是关于模板函数的,书是《c++程序设计从入门到精通》,我是看着例子多才会看的,不求精通(一般精通的都很假)书是清华大学出版社出版的,明日科技的书。附上例子给大家

例子是有错的,当初怀疑是编译器的问题,于是屁颠屁颠地使用了VC6.0编译看能不能行,结果是一样的,以下是编译信息

2444D:\360云盘备份\各类语言代码集合\DevC++程序集\调试.cpp[Error] call of overloaded 'min(int, int)' is ambiguous

重载函数存在歧义,什么原因造成的呢?书中竟然给运行成功了,不知道是为什么?查到一篇博客,以下是链接

博文出处

附上改后的代码

#include<iostream>
#include<string>
template<class Type>
Type min(Type a,Type b)
{
if(a<b)
return a;
else
return b;

}
char *min(char *a, char *b)
{
if(strcmp(a,b))
return b;
else
return a;
}

int main()
{

std::cout<<"The minimum value is "<<std::min(10,1)<<std::endl;
std::cout<<"The minimum value is "<<std::min('a','b')<<std::endl;
std::cout<<"The minimum value is "<<std::min("hi","mr")<<std::endl;

}

以下是错误的书中例子代码

由于编辑的问题,请仔细比对下两篇代码,问题应该不大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++小细节 c语言