7. 修改程序清单8.14,使其使用两个名为SumArray()的模板函数来返回数组元素的总和,而不是显示数组的内容。程序应显示thing的总和以及所有debt的总和。?
// tempover.cpp --- template overloading
#include <iostream>
template <typename T>
T SumArray(T arr[], int n);
template <typename T>
T SumArray(T* arr[], int n);
struct debts
{
char name[50];
double amount;
};
int main()
{
using namespace std;
int things[6] = { 13, 31, 103, 301, 310, 130 };
struct debts mr_E[3] =
{
{"Ima Wolfe", 2400.0},
{"Ura Foxe", 1300.0},
{"Iby Stout", 1800.0}
};
double* pd[3];
// set pointers to the amount members of the structures in mr_E
for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;
cout << SumArray(things, 6) << endl;
cout << SumArray(pd, 3) << endl;
return 0;
}
template <typename T>
T SumArray(T arr[], int n) {
T sum=arr[0];
for (int i = 1; i < n; i++)
sum += arr[i];
return sum;
}
template <typename T>
T SumArray(T* arr[], int n) {
T sum = *arr[0];
for (int i = 1; i < n; i++)
sum += *arr[i];
return sum;
}
|