📄 change814.cpp
字号:
// 7.修改程序清单8.14,使模板函数返回数组元素的总和,而不是显示数组的内容.
// 程序thing的总和以及所有debt的总和.
#include <iostream>
template <typename T> //template A
T ShowArray (T arr[], int n);
template <typename T> //template B
T ShowArray (T * arr[], int n);
struct debts
{
char name[50];
double amount;
};
int main(void)
{
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 the arr mr_E
for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;
cout<<"Listing Mr. E's counts of things:\n";
//things is an array of int
ShowArray(things,6); //uses template A
cout<<"Listing Mr. E's debts:\n";
//pd is an array of pointers to double
ShowArray (pd,3); //uses template B(more specialized)
return 0;
}
template <typename T>
T ShowArray (T arr[],int n)
{
using namespace std;
T total = 0;
cout<<"template A\n";
for (int i = 0; i < n; i++)
total +=arr[i];
return total;
}
template <typename T>
T ShowArray (T * arr[], int n)
{
using namespace std;
T total = 0;
cout<< "template B\n";
for (int i = 0; i < n; i++)
total += *arr[i];
return total;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -