【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

相关推荐
badhope几秒前
Python、C、Java 终极对决!谁主沉浮?谁将消亡?
java·c语言·开发语言·javascript·人工智能·python·github
big_rabbit05021 分钟前
java面试题总结2
java·开发语言
m0_518019481 分钟前
分布式系统安全通信
开发语言·c++·算法
轩情吖4 分钟前
MySQL内置函数
android·数据库·c++·后端·mysql·开发·函数
2501_930707785 分钟前
使用C#代码将 PDF 转换为 PostScript(PS)格式
开发语言·pdf·c#
金山几座6 分钟前
C#学习记录-泛型
开发语言·学习·c#
小邓睡不饱耶10 分钟前
实战教程:Python爬取北京新发地农产品价格数据并存储到MySQL
开发语言·python·mysql
EnCi Zheng14 分钟前
P1B-Python环境配置基础完全指南-Windows系统安装与验证
开发语言·windows·python
小陈phd14 分钟前
多模态大模型学习笔记(十九)——基于 LangChain+Faiss的本地知识库问答系统实战
开发语言·c#
重庆兔巴哥15 分钟前
如何检查Java环境变量是否配置成功?
java·开发语言