【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

相关推荐
无双@几秒前
高并发内存池9 —— Page Cache 回收
c++·线程·秋招·项目·高并发内存池·c++项目·内存池
缺点内向几秒前
Java: 为PDF批量添加图片水印实用指南
java·开发语言·pdf
西西学代码15 分钟前
Flutter---异步编程
开发语言·前端·javascript
卡提西亚20 分钟前
C++笔记-26-类模板
c++·笔记
song85460113421 分钟前
锁的初步学习
开发语言·python·学习
重整旗鼓~27 分钟前
38.附近商户实现
java·开发语言
沐怡旸35 分钟前
【穿越Effective C++】条款19:设计class犹如设计type——用户定义类型的艺术与科学
c++·面试
一个不知名程序员www38 分钟前
算法学习入门---模拟(C++)
c++·算法
夜月yeyue1 小时前
嵌入式开发中的 Git CI/CD
c++·git·单片机·嵌入式硬件·ci/cd·硬件架构
❀͜͡傀儡师1 小时前
JDK 25 新特性速览
java·开发语言