【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

相关推荐
shykevin1 小时前
python开发Streamable HTTP MCP应用
开发语言·网络·python·网络协议·http
我不是程序猿儿1 小时前
【C#】 lock 关键字
java·开发语言·c#
漫路在线1 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
小辉懂编程2 小时前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
醍醐三叶3 小时前
C++类与对象--2 对象的初始化和清理
开发语言·c++
向上的车轮3 小时前
MATLAB学习笔记(七):MATLAB建模城市的雨季防洪排污的问题
笔记·学习·matlab
Magnum Lehar4 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld8574 小时前
java集合
java·开发语言·windows
成功人chen某4 小时前
配置VScodePython环境Python was not found;
开发语言·python
前端小崔4 小时前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器