我有以下代码:
#include <iostream>
using namespace std;
template<class T>
T max(T *data,int len){
int i;
T Max=data[0];
for (int i=1;i<len;i++){
if (data[i]>max){
Max=data[i];
}
}
return Max;
}
int mai(){
int i[]={12,34,10,9,56,78,30};
int len=sizeof(i)/sizeof(i[0]);
cout<<max(i,len)<<"\n";
return 0;
}
但是当我编译它时,我得到以下错误:
generic_max, Configuration: Debug Win32 ------
1>Build started 7/29/2010 1:03:25 AM.
1>InitializeBuildStatus:
1> Touching "Debug\generic_max.unsuccessfulbuild".
1>ClCompile:
1> generic_max.cpp
1>c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(10): error C2563: mismatch in formal parameter list
1> c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(22) : see reference to function template instantiation 'T max<int>(T *,int)' being compiled
1> with
1> [
1> T=int
1> ]
1>c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(10): error C2568: '>' : unable to resolve function overload
1> c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(4): could be 'T max(T *,int)'
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(2086): or 'const _Ty &std::max(const _Ty &,const _Ty &,_Pr)'
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(2078): or 'const _Ty &std::max(const _Ty &,const _Ty &)'
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.95
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
请帮我解决这个问题。
答案 0 :(得分:4)
C ++区分大小写。
#include <iostream>
// Note the omission of `using namespace std;`. The declaration can
// introduce clashes if one of your functions happen to have the same name
// as the functions in the std namespace.
template<class T>
T max(T *data,int len) {
//int i; <-- Not needed? The for loop already has an `i` declared in it.
T Max=data[0];
for (int i=1;i<len;i++) {
/****** Note `Max`, not `max` ******/
// The typo in your code snippet is what's causing the C2563.
// `max` (in this context) refers to the function
// `template<class T> T max(T *data,int len)` that has been declared.
// `Max` refers to the variable declared in this function.
// (For the sake of readability, variable names should not similar
// to the function name).
if (data[i]>Max) {
Max=data[i];
}
}
return Max;
}
/****** Note `main()`, not `mai()` ******/
int main() {
int i[]={12,34,10,9,56,78,30};
int len=sizeof(i)/sizeof(i[0]);
// `cout` should be just qualified with `std::` instead of
// `using namespace std`.
std::cout<<max(i,len)<<"\n";
return 0;
}
答案 1 :(得分:4)
您的max
函数与标准C ++函数std::max
冲突,因为您已在程序顶部编写using namespace std
,这会将std
命名空间中的所有内容都放入默认命名空间。编译器无法判断您是想要调用max
还是某个版本的std::max
。
更改您的功能名称,或删除using namespace std
并使用std
在std::
命名空间中明确为您的程序中的内容添加前缀。
答案 2 :(得分:0)
if(data [i]&gt; max) - 将max更改为Max
答案 3 :(得分:0)
在第10行中,您可能是>Max
而不是>max
。