【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++ std::set
c++
侃侃_天下1 小时前
最终的信号类
开发语言·c++·算法
博笙困了2 小时前
AcWing学习——差分
c++·算法
echoarts2 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
2303_Alpha2 小时前
SpringBoot
笔记·学习
Aomnitrix2 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
萘柰奈2 小时前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity
青草地溪水旁2 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁2 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥3 小时前
C++ std::vector
c++