C++Primer Plus 编程练习8.8,练习7函数重载和函数模板重载的实现

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值