【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

相关推荐
智商低情商凑23 分钟前
Go学习之 - Goroutines和channels
开发语言·学习·golang
半桶水专家23 分钟前
Go 语言时间处理(time 包)详解
开发语言·后端·golang
编程点滴24 分钟前
Go 重试机制终极指南:基于 go-retry 打造可靠容错系统
开发语言·后端·golang
实心儿儿35 分钟前
C++ —— 模板进阶
开发语言·c++
敲敲了个代码1 小时前
CSS 像素≠物理像素:0.5px 效果的核心密码是什么?
前端·javascript·css·学习·面试
萧鼎1 小时前
Python PyTesseract OCR :从基础到项目实战
开发语言·python·ocr
go_bai2 小时前
Linux-线程2
linux·c++·经验分享·笔记·学习方法
二川bro2 小时前
第57节:Three.js企业级应用架构
开发语言·javascript·架构
sali-tec2 小时前
C# 基于halcon的视觉工作流-章62 点云采样
开发语言·图像处理·人工智能·算法·计算机视觉
j_xxx404_2 小时前
C++:继承(概念及定义|作用域|基类与派生类转换|默认成员函数|与友元、静态成员关系|多继承|组合)
数据结构·c++