【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

相关推荐
我是苏苏1 小时前
C#基础:Winform桌面开发中窗体之间的数据传递
开发语言·c#
斐波娜娜1 小时前
Maven详解
java·开发语言·maven
小码氓2 小时前
Java填充Word模板
java·开发语言·spring·word
暮鹤筠2 小时前
[C语言初阶]操作符
c语言·开发语言
蜉蝣之翼❉4 小时前
CRT 不同会导致 fopen 地址不同
c++·mfc
Boilermaker19924 小时前
【Java EE】Mybatis-Plus
java·开发语言·java-ee
aramae4 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
Tony小周4 小时前
实现一个点击输入框可以弹出的数字软键盘控件 qt 5.12
开发语言·数据库·qt
lixzest4 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
fen_fen5 小时前
学习笔记(32):matplotlib绘制简单图表-数据分布图
笔记·学习·matplotlib