【C++ Primer Plus习题】8.7

问题:




解答:

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

相关推荐
Alair‎1 小时前
【无标题】
开发语言
Mr.Jessy4 小时前
JavaScript高级:构造函数与原型
开发语言·前端·javascript·学习·ecmascript
云栖梦泽6 小时前
鸿蒙应用签名与上架全流程:从开发完成到用户手中
开发语言·鸿蒙系统
爱上妖精的尾巴6 小时前
6-4 WPS JS宏 不重复随机取值应用
开发语言·前端·javascript
玄斎8 小时前
MySQL 单表操作通关指南:建库 / 建表 / 插入 / 增删改查
运维·服务器·数据库·学习·程序人生·mysql·oracle
小鸡吃米…8 小时前
Python 列表
开发语言·python
kaikaile19958 小时前
基于C#实现一维码和二维码打印程序
开发语言·c#
我不是程序猿儿9 小时前
【C#】画图控件的FormsPlot中的Refresh功能调用消耗时间不一致缘由
开发语言·c#
rit84324999 小时前
C# Socket 聊天室(含文件传输)
服务器·开发语言·c#
kk哥88999 小时前
C++ 对象 核心介绍
java·jvm·c++