C++primer plus第六版课后编程题答案8.8

时间:2022-02-26 14:41:47

8.8

#include <iostream>
using namespace std;
template <typename T>
T SumArray(T arr[],int n)
{
	T sum=0;
	for(int i=0;i<n;i++)
		sum+=arr[i];
	return sum;
};
template <typename T>
T SumArray(T *arr[],int n)//arr是指向指针数组的指针
{
		T sum=0;
		for(int i=0;i<n;i++)
			sum+=*arr[i];	//arr[i]是一个指针,+*之后才是其中的数值;
		return sum;
};
struct debts{
	char name[20];
	double amount;
};

void main87()
{
	int things[6]={13,31,103,301,310,130};
	struct debts mr_E[3]={
		{"Ima Wolfe",2400.0},
		{"Ura Foxe",1300.0},
		{"Tby Stout",1800.0}
	};
	double *pd[3];
	for(int i=0;i<3;i++)
		pd[i]=&mr_E[i].amount;//取址之后才能赋给指针

	cout<<"The sum is"<<SumArray(things,6)<<endl;
	cout<<"The sum is"<<SumArray(pd,3)<<endl;





}