问题:
解答:
cpp
#include <iostream>
using namespace std;
template <typename T>
T SumArray(T arr[], int n)
{
T sum = arr[0] - arr[0];
for (int i = 0; i < n; i++)
{
sum += arr[i];
}
return sum;
}
template <typename T>
T SumArray(T *arr[], int n)
{
T sum = *arr[0]-*arr[0];
for (int i = 0; i < n; i++)
{
sum += *arr[i];
}
return sum;
}
struct debts
{
char name[50];
double amount;
};
int main()
{
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];
for (int i = 0; i < 3; i++)
{
pd[i] = &mr_E[i].amount;
}
cout << "things的总数为:" << SumArray(things, 6) << endl;
cout << "debts的总数为:" << SumArray(pd, 3) << endl;
return 0;
}
运行结果:
考查点:
- 模版函数重载
注意:
- 不知道具体类型,可以自己减自己赋初始值
2024年9月1日22:22:56