c++模板问题
请问,为什么这个函数运行结果是这个啊?#include<iostream>using namespace std;
template <typename T>
T average(T*array, int n = 0)
{
T sum = 0;
T aver = 0;
for (int i = 0; i <= n; i++)
{
sum += array;
}
aver = sum / n;
return aver;
};
int main()
{
int iarray[] = { 1,2,3,4,5,6,7,8,9 };
double darray[] = { 1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9 };
int int_iarray = average(iarray, 9);
double double_darray = average(darray, 9);
cout <<int_iarray<< endl;
cout << double_darray<< endl;
return 0;
} 不是代码的问题吧
$ g++ -g -Wall -o main main.cpp
$ ./main
5
5.5
$
改成这样试试:
#include<iostream>
using namespace std;
template <typename T>
T average(T*array, int n = 0)
{
T sum = 0;
T aver = 0;
for (int i = 0; i <= n; i++)
{
sum += array;
}
aver = sum / n;
return aver;
};
int main()
{
int iarray[] = { 1,2,3,4,5,6,7,8,9 };
double darray[] = { 1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9 };
int int_iarray = average<int>(iarray, 9);
double double_darray = average<double>(darray, 9);
cout <<int_iarray<< endl;
cout << double_darray<< endl;
return 0;
}
页:
[1]