<span style="font-family: Arial; background-color: rgb(255, 255, 255);">
</span>
<span style="font-family: Arial; background-color: rgb(255, 255, 255);">修改程序清单8.14(如下),使模板函数返回数组元素的总和,</span><span style="font-family: Arial; background-color: rgb(255, 255, 255);">而不是显示数组的内容.程序thing的总和以及所有debt的总和.</span>
<span style="font-family: Arial; background-color: rgb(255, 255, 255);"></span><pre name="code" class="cpp">#include "stdafx.h"
#include <iostream>
template<typename T>
void ShowArray(T arr[], int n);
template <typename T>
void ShowArray(T* arr[], int n);
struct debts
{
char name[50];
double amount;
};
int _tmain(int argc, _TCHAR* argv[])
{
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];
for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;
cout << "Listing Mr.E' counts of things:\n";
ShowArray(things, 6);
cout << "Listing Mr.E's debts:\n";
ShowArray(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;
}
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;
}
修改后的程序:
#include "stdafx.h"
#include <iostream>
template<typename T>
void ShowArray(T arr[], int n);
template <typename T>
void ShowArray(T* arr[], int n);
struct debts
{
char name[50];
double amount;
};
int _tmain(int argc, _TCHAR* argv[])
{
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];
for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;
cout << "Listing Mr.E' sum counts of things:\n";
ShowArray(things, 6);
cout << "Listing Mr.E's sum debts:\n";
ShowArray(pd, 3);
return 0;
}
template<typename T>
void ShowArray(T arr[], int n)
{
using namespace std;
T s = 0;
cout << "template A\n";
for (int i = 0; i < n; i++) s += arr[i];
cout << s << ' ';
cout << endl;
}
template<typename T>
void ShowArray(T * arr[], int n)
{
using namespace std;
T s = 0;
cout << "template B\n";
for (int i = 0; i < n; i++) s += *arr[i];
cout << s << ' ';
cout << endl;
}