我编写了这段代码,如果我取消注释第二行,我会收到错误 - "模板参数推断/替换失败:".是因为C++中泛型函数的一些限制吗?此外,我的程序不会打印数组的浮动答案b.有什么我可以做的吗?(抱歉在单个帖子中提出2个问题.)
PS:我刚刚开始学习C++.
#include <iostream>
using namespace std;
template <class T>
T sumArray( T arr[], int size, T s =0)
{
int i;
for(i=0;i<size;i++)
{ s += arr[i];
}
return s;
}
int main()
{
int a[] = {1,2,3};
double b[] = {1.0,2.0,3.0};
cout << sumArray(a,3) << endl;
cout << sumArray(b,3) << endl;
cout << sumArray(a,3,10) << endl;
//cout << sumArray(b,3,40) << endl; //uncommenting this line gives error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑1:更改40到40.0后,代码工作.这是我得到的输出:
6
6
16
46
我仍然没有得到第二种情况下的浮动答案.有什么建议吗?