【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

相关推荐
狐凄6 分钟前
Python实例题:Python计算概率论
开发语言·python·概率论
liujing102329296 分钟前
Day09_刷题niuke20250609
java·c++·算法
Y3174298 分钟前
python Day46 学习(日志Day15复习)
python·学习·机器学习
Bardb12 分钟前
02__C++的基本语法
c++·qt
学不会就看28 分钟前
selenium学习实战【Python爬虫】
python·学习·selenium
q5673152330 分钟前
分布式增量爬虫实现方案
开发语言·分布式·爬虫·python
勤奋的知更鸟36 分钟前
LLaMA-Factory和python版本的兼容性问题解决
开发语言·python·llama-factory
CIb0la38 分钟前
Ai自动补全编程工具:llama vscode
运维·开发语言·学习·测试工具·程序人生
1candobetter1 小时前
JAVA后端开发——多租户
java·开发语言
2301_804774491 小时前
回溯算法学习
学习