2011-05-04 44 views
3

我上template.This代碼VC6下通過一些問題,但下克++失敗。 有沒有人可以告訴我原因?謝謝。呼叫的重載「分鐘(INT&,INT&)」不明確

#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/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf "/usr/bin/make" -f nbproject/Makefile-Debug.mk dist/Debug/GNU-MacOSX/traincpp mkdir -p build/Debug/GNU-MacOSX rm -f build/Debug/GNU-MacOSX/newmain.o.d g++ -c -g -MMD -MP -MF build/Debug/GNU-MacOSX/newmain.o.d -o build/Debug/GNU-MacOSX/newmain.o newmain.cpp newmain.cpp: In function 'int main()': newmain.cpp:13: error: call of overloaded 'min(int&, int&)' is ambiguous newmain.cpp:5: note: candidates are: T min(T, T) [with T = int] /usr/include/c++/4.2.1/bits/stl_algobase.h:182: note: const _Tp& std::min(const _Tp&, const _Tp&) [with _Tp = int] newmain.cpp:14: error: call of overloaded 'min(float&, float&)' is ambiguous newmain.cpp:5: note: candidates are: T min(T, T) [with T = float] /usr/include/c++/4.2.1/bits/stl_algobase.h:182: note: const _Tp& std::min(const _Tp&, const _Tp&) [with _Tp = float] newmain.cpp:15: error: call of overloaded 'min(double&, double&)' is ambiguous newmain.cpp:5: note: candidates are: T min(T, T) [with T = double] /usr/include/c++/4.2.1/bits/stl_algobase.h:182: note: const _Tp& std::min(const _Tp&, const _Tp&) [with _Tp = double] make[2]: * [build/Debug/GNU-MacOSX/newmain.o] Error 1 make[1]: [.build-conf] Error 2 make: ** [.build-impl] Error 2

生成 失敗 (退出值 2, 總計時間: 623毫秒)

回答

11

這是因爲你已經輸入的所有std namespace,這是一個no-no的。注意其他候選人是模板std::min。取出using namespace std;並導入選擇符號:

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

或限定它們:

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

+1 - [爲什麼使用命名空間std被認爲是不好(http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c) – 2011-05-04 18:14:19

+0

對不起我的愚蠢錯誤。 – Shisoft 2011-05-04 18:15:55

1

也許你已經有MIN()在G ++的定義。

+1

不大可是,但絕對。 'min'是'std'命名空間中的標準C++模板函數,它被導入。 – 2011-05-04 18:13:13

+0

可能是因爲必須是一個不知道它的初學者! – 2011-05-04 18:14:50

+0

賓果!我在CPP – Shisoft 2011-05-04 18:23:14

1

您的iostream包括似乎也引入標準min調用以及編譯器無法弄清楚,如果你想標準的(因爲你的using namespace)或你自己的。只需刪除自己的min並使用標準庫的版本。

+0

這些include包含'std :: min',這很好。問題是'使用命名空間std' – 2011-05-04 18:17:51

+0

這是大學課程的做法,我已經改變解決了這個問題的名稱。 – Shisoft 2011-05-04 18:24:36

1

,而不是寫的std ::法院,U可以使用命名空間std中,而在另一個命名空間創建功能分鐘,說ABC ...所以現在當u調用函數分鐘,只寫ABC ::分鐘..這應該可以解決你的問題。