对超载'min(int&, int&)'的调用不明确

call of overloaded 'min(int&, int&)' is ambiguous

本文关键字:int 不明确 调用 超载 min      更新时间:2023-10-16

我在模板上有一些问题。此代码在vc6下通过,但在g++下失败。有人能告诉我原因吗?谢谢。

#include<iostream>
using namespace std;
template<class T>
T min(T x, T y) {
    return (x < y ? x : y);
}
int main() {
    int i1 = 23, i2 = 15, i;
    float f1 = 23.04, f2 = 43.2, f;
    double d1 = 0.421342, d2 = 1.24342343, d;
    i = min(i1, i2);
    f = min(f1, f2);
    d = min(d1, d2);
    cout << "The smaller of " << i1 << " and " << i2 << " is " << i << endl;
    cout << "The smaller of " << f1 << " and " << f2 << " is " << f << endl;
    cout << "The smaller of " << d1 << " and " << d2 << " is " << d << endl;
}

"/usr/bin/做出"- fnbproject/Makefile-Debug。可QMAKE =子项目= .build-conf"/usr/bin/"- fnbproject/Makefile-Debug.mkdist/调试/GNU-MacOSX/traincpp mkdir-f build/Debug/GNU-MacOSX/newmain.od g + +-c -g -MMD -MP -MF build/Debug/GNU-MacOSX/newmain.od - o构建/调试/GNU-MacOSX/newmain.onewmain.cpp:在功能中` int main() `: newmain.cpp:13:错误:重载` min(int&, int&) `的调用newmain.cpp:5:候选者为:T min(T, T)[其中T =int)/usr/include/c + +/4.2.1/位/stl_algobase.h准备:182:注:const _Tp&std::min(const _Tp&, const _Tp&) [with[_Tp = int] newmain.cpp:14:错误:调用重载的'min(float&, float&)'是歧义newmain.cpp:5:候选者为:T min(T, T)[其中T =浮动)/usr/include/c + +/4.2.1/位/stl_algobase.h准备:182:注:const _Tp&std::min(const _Tp&, const _Tp&) [with[_Tp = float] newmain.cpp:15:错误:调用重载的'min(double&;Double&)'是有歧义的newmain.cpp:5:注:候选者为:T min(T, T)[with T = double]/usr/include/c + +/4.2.1/位/stl_algobase.h准备:182:注:const _Tp&std::min(const _Tp&, const _Tp&) [withmake[2]: * [build/Debug/GNU-MacOSX/newmain.o]错误1 make[1]: [.build-conf]错误2:**[。build-impl)错误2

生态环境

生态环境

生态环境

生态环境

生态环境

这是因为您已经导入了所有的std名称空间,这是不允许的。注意,其他候选模板是模板std::min。删除using namespace std;并导入选择符号:

using std::cout;
using std::endl;

或限定它们:

std::cout << "The smaller of " << i1 << " and " << i2 << " is " << i << std::endl;

您可能已经在g++中定义了min()

您的iostream包含似乎也引入了标准min调用,编译器无法确定您是否想要标准的(因为您的using namespace)或您自己的。只需删除自己的min并使用标准库的版本。

不要写std::cout,你可以使用命名空间std,并在另一个命名空间中创建函数min,比如abc…所以现在当你调用函数min时,只需写abc::min…这应该能解决你的问题。

函数swap()iostream中已经存在。因此,它与swap()函数冲突。您可能必须指定要使用哪个swap()或更改swap函数的名称,如swap1(), swap2()等。您可以将任何字母更改为大写,如 swap ()这可以解决问题,而无需删除using namespace std;

否则,只需删除using namespace std'并输入

using std :: cout;
using std :: endl;

代替,或者写成-

std :: cout << "After swapping - a = " << a << ", b = " << b << std :: endl;

就是这样。谢谢你。