7.修改程序清单 8.14,使其使用两个名为 SumAray0的模板函数来返回数组元素的总和,而不是显示数组的内容。
程序应显示 thing的总和以及所有 debt的总和。
练习本测试题之前,需要先完成8.14的代码,进一步改造
#pragma region 练习7.cpp
/*
*/
#if 1
#include <iostream>
#include <string>
函数列表
template<typename T>
void showArray(T arr[], int n);
template<typename T>
void SumArray(T arr[], int n);新增加的
template<typename T>
void showArray(T* arr[], int n);
template<typename T>
void 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},
{"Uar Foxe",1300.0},
{"Iby Stout",1800.0}
};
double* pd[3];
for (int i = 0; i < 3; i++)
{
pd[i] = &mr_E->amount;
}
cout << "Listing Mr.E's counts of things;\n";
showArray(things, 6);
SumArray(things, 6);
cout << "Listing Mr.E's debts:\n";
showArray(pd, 3);
SumArray(pd, 3);
return 0;
}
模板的实现
template<typename T>
void showArray(T arr[], int n)
{
using namespace std;
cout << "template A\n";
for (int i = 0; i < n; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
}
本作业新增加的函数1
template<typename T>
void SumArray(T arr[], int n)
{
using namespace std;
T sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
}
cout << "数组元素的总和为:" << sum << endl;
}
template<typename T>
void showArray(T* arr[], int n)
{
using namespace std;
cout << "template B\n";
for (int i = 0; i < n; i++)
{
cout << *arr[i] << ' ';
}
cout << endl;
}
本作业新增加的函数2
template<typename T>
void SumArray(T* arr[], int n)
{
using namespace std;
T sum = 0;
for (int i = 0; i < n; i++)
{
sum += *arr[i];
}
cout << "数组元素的总和为:" << sum << endl;
}
#endif
#pragma endregion