《C++PrimePlus》第8章 函数探幽

news2024/9/23 13:19:06

8.1 内联函数

使用内联函数

#include <iostream>
using namespace std;

inline double square(double x) { return x * x; }

int main(){
	double a;
	a = square(5.0);
	cout << "a = " << a << endl;
	return 0;
}

8.2 引用变量

将引用用作函数参数(使用const)

#include <iostream>
using namespace std;
double cube(const double &ra);

int main(){
	double x = 3.0;
	cout << cube(x) << " = cube of " << x << endl;
	cout << cube(5) << " = cube of " << "5" << endl;
	cout << cube(x+5) << " = cube of " << x+5 << endl;
	return 0;
}

double cube(const double &ra) {
	return ra*ra*ra;
}

将引用用于结构

#include <iostream>
#include <string>
using namespace std;

struct free_throws {
	string name;
	int made;
	int attempts;
	float percent;
};

void set_pc(free_throws &ft);
void display(const free_throws &ft);
free_throws &accumulate(free_throws &target, const free_throws &source);

int main(){
	free_throws one = { "Rick", 13, 14 }; // 最后一个值没赋值,为空
	free_throws two = { "Jack", 10, 16 };
	free_throws team = { "All", 0, 0 };
	set_pc(one); // 赋值
	display(one); // 展示
	display(accumulate(team, one)); // 汇总
	return 0;
}

void set_pc(free_throws &ft) { // 要修改原始数据,不加const
	if (ft.attempts != 0)
		ft.percent = 100.0 * float(ft.made) / float(ft.attempts);
	else
		ft.attempts = 0;
}

void display(const free_throws &ft) {
	cout << "Name: " << ft.name << endl;
	cout << "Made: " << ft.made << '\t';
	cout << "Attempts: " << ft.attempts << '\t';
	cout << "Percent: " << ft.percent << endl;
}
// 把函数的返回值定义为结构体引用
free_throws &accumulate(free_throws &target, const free_throws &source) {
	target.attempts += source.attempts;
	target.made += source.made;
	set_pc(target);
	return target;
}

将引用用于类的对象

#include <iostream>
#include <string>
using namespace std;
string version1(const string &s1, const string &s2);
const string &version2(string &s1, const string &s2);
// const string &version3(string &s1, const string &s2);

int main(){
	string input;
	string copy;
	string result;
	cout << "Enter a string: ";
	getline(cin, input);
	copy = input;
	cout << "You string: " << input << endl;
	result = version1(input, "***"); // 在字符串前后都加上***
	cout << "Your string enhanced: " << result << endl;
	cout << "Your input: " << input << endl;
	cout << "-------------------------------------" << endl;
	result = version2(input, "###");
	cout << "Your string enhanced: " << result << endl;
	cout << "Your input: " << input << endl;
	//cout << "-------------------------------------" << endl;
	//input = copy;
	//result = version3(input, "@@@");
	//cout << "Your string enhanced: " << result << endl;
	//cout << "Your input: " << input << endl;
	return 0;
}
// const string &s2 对应的是 "***"
// 当使用const限定符时,会产生临时变量并进行类型转换
string version1(const string &s1, const string &s2) {
	string temp;
	temp = s2 + s1 + s2;
	return temp;
}
// 返回一个string类的对象的引用
const string &version2(string &s1, const string &s2) {
	s1 = s2 + s1 + s2;
	return s1;
}

/*错误的使用方法:返回临时变量的引用
const string &version3(string &s1, const string &s2) {
	string temp;
	temp = s2 + s1 + s2;
	return temp;
}
*/

对象、继承和引用

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
const int LIMIT = 5;
void file_it(ostream &os, double fo, const double fe[], int n);

int main(){
	fstream fout;
	// 先在路径中里新建这个txt文件
	const char *fn = "ep-data.txt";
	fout.open(fn);
	if (!fout.is_open()) {
		cout << "Can't open " << fn << "." << endl;
		exit(EXIT_FAILURE);
	}

	double objective; // 物镜的焦距
	cout << "Enter the focal length of telescope objective in mm: ";
	cin >> objective;
	double eps[LIMIT]; // 目镜的焦距
	for (int i = 0; i < LIMIT; i++) {
		cout << "Eyepieces #" << i + 1 << ": ";
		cin >> eps[i];
	}

	file_it(cout, objective, eps, LIMIT); // 在终端上显示
	file_it(fout, objective, eps, LIMIT); // 在文件中显示
	cout << "Done." << endl;
	return 0;
}
// ostream &os 基类的引用,可以指向基类的对象,也可以指向派生类的对象
void file_it(ostream &os, double fo, const double fe[], int n) {
	os << "Focal length of objective: " << fo << endl;
	os << "f.l. eyepieces" << " magnification" << endl;
	for (int i = 0; i < n; i++) {
		os << "    " << fe[i] << "    " << int(fo / fe[i] + 0.5) << endl;
	}
}

8.3 默认参数

默认参数的用法(取出字符串的前n个值)

#include <iostream>
using namespace std;
const int ArSize = 80;
char *left(const char *str, int n = 1); // 默认参数n=1

int main(){
	char sample[ArSize];
	cout << "Enter a string: " << endl;
	cin.get(sample, ArSize);

	char *ps = left(sample, 4);
	cout << ps << endl;
	delete[] ps; // 注意new和delete成对出现
	ps = left(sample); // 使用默认参数
	cout << ps << endl;
	delete[] ps;

	return 0;
}

char *left(const char *str, int n) {
	int m = 0;
	while (m < n && str[m] != '\0') m++; // 确定字符串长度
	char *p = new char[m + 1];
	int i;
	for (i = 0; i < m; i++) {
		p[i] = str[i];
	}
	p[i] = '\0'; // 最后要补上一个空字符
	return p;
}

8.4 函数重载

函数重载示例(取出字符串/数字的前n个值)

#include <iostream>
using namespace std;
const int ArSize = 80;
char *left(const char *str, int n = 1);
unsigned long left(unsigned long num, unsigned int ct);

int main(){
	const char *trip = "Hawaii";
	unsigned long n = 12345678;
	int i;
	char *temp;
	for (i = 0; i < 10; i++) {
		cout << left(n, i) << endl;
		temp = left(trip, i);
		cout << temp << endl;
		delete[] temp;
	}
	return 0;
}

char *left(const char *str, int n) {
	int m = 0;
	while (m < n && str[m] != '\0') m++; // 确定字符串长度
	char *p = new char[m + 1];
	int i;
	for (i = 0; i < m; i++) {
		p[i] = str[i];
	}
	p[i] = '\0'; // 最后要补上一个空字符
	return p;
}

unsigned long left(unsigned long num, unsigned int ct) {
	unsigned long n = num;
	unsigned int digits = 1;
	if (num == 0 || ct == 0) return 0; // 特殊情况
	while (n /= 10) digits++; // 判断数字有几位
	if (digits > ct) {
		ct = digits - ct; // 要除几次10
		while (ct--) num /= 10;
		return num;
	}
	else
		return num;
}

8.5 函数模板

函数模板示例(交换两个数的值)

#include <iostream>
using namespace std;
template <typename T>
void Swap(T &a, T &b);

int main(){
	int i = 10;
	int j = 20;

	cout << "i, j = " << i << ", " << j << "." << endl;
	Swap(i, j);
	cout << "Afer swap, i, j = " << i << ", " << j << "." << endl;
	
	double x = 24.5;
	double y = 81.7;
	cout << "x, y = " << x << ", " << y << "." << endl;
	Swap(x, y);
	cout << "Afer swap, x, y = " << x << ", " << y << "." << endl;

	return 0;
}

template <typename T>
void Swap(T &a, T &b) {
	T temp;
	temp = a;
	a = b;
	b = temp;
}

重载的模板示例(交换两个数或两个数组)

#include <iostream>
using namespace std;
template <typename T>
void Swap(T &a, T &b);
template <typename T>
void Swap(T a[], T b[], int n);
const int LIMIT = 8;
void show(int arr[], int n);


int main(){
	int i = 10;
	int j = 20;
	cout << "i, j = " << i << ", " << j << "." << endl;
	Swap(i, j);
	cout << "Afer swap, i, j = " << i << ", " << j << "." << endl;
	
	int d1[LIMIT] = { 0,7,0,4,1,7,7,6 };
	int d2[LIMIT] = { 0,7,2,0,1,9,6,9 };
	cout << "Original arrays: " << endl;
	show(d1, LIMIT);
	show(d2, LIMIT);
	Swap(d1, d2, LIMIT);
	cout << "After swap: " << endl;
	show(d1, LIMIT);
	show(d2, LIMIT);

	return 0;
}

template <typename T>
void Swap(T &a, T &b) {
	T temp;
	temp = a;
	a = b;
	b = temp;
}

template <typename T>
void Swap(T a[], T b[], int n) {
	T temp;
	for (int i = 0; i < n; i++) {
		temp = a[i];
		a[i] = b[i];
		b[i] = temp;
	}
}

void show(int arr[], int n) {
	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";
	}
	cout << endl;
}

调用函数时的最佳匹配(打印数组内容)

#include <iostream>
using namespace std;
template <typename T>
void ShowArray(T arr[], int n);
template <typename T>
void ShowArray(T *arr[], int n);

struct debts {
	char name[50]; // 名字
	double amount; // 数量
};

int main(){
	int things[6] = { 13,31,103,301,310,130 };
	struct debts mr_E[3] = 
	{
		{"Rick", 2400.00},
		{"Jack", 1300.0},
		{"Rose", 1800.0}
	};
	double *pd[3]; // 3个元素的数组,每个元素都是指针
	for (int i = 0; i < 3; i++) {
		pd[i] = &mr_E[i].amount;
	}
	ShowArray(things, 6);
	// 更匹配 void ShowArray(T *arr[], int n)
	// 会打印出来指针指向的数值
	ShowArray(pd, 3); 
	return 0;
}

template <typename T>
void ShowArray(T arr[], int n) {
	cout << "template A:" << endl;
	for (int i = 0; i < n; i++)
		cout << arr[i] << " ";
	cout << endl;
}

template <typename T>
void ShowArray(T *arr[], int n) {
	cout << "template B:" << endl;
	for (int i = 0; i < n; i++) 
		cout << *arr[i] << " ";
	cout << endl;
}

引导编译器使用指定函数(打印较小的值)

#include <iostream>
using namespace std;
template <class T>

T lesser(T a, T b) { // 函数1 返回较小值
	return a < b ? a : b;
}

int lesser(int a, int b) { // 函数2 返回绝对值的较小值
	a = a < 0 ? -a : a;
	b = b < 0 ? -b : b;
	return a < b ? a : b;
}

int main(){
	int m = 20, n = -30;
	double x = 15.5, y = -25.9;
	// 非模板函数优先,调用的是函数2
	cout << lesser(m, n) << endl;
	// 非模板函数不是最优(要进行类型转换),调用的是函数1
	cout << lesser(x, y) << endl;
	// 尖括号<>告诉编译器使用模板函数,调用函数1
	cout << lesser<>(m, n) << endl;
	// 把x和y强制转换为int类型,再使用模板函数2
	cout << lesser<int>(x, y) << endl;
	return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1248902.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

在JVM中 判定哪些对象是垃圾?

目录 垃圾的条件 1、引用计数法 2、可达性分析 3、强引用 4、软引用 5、弱引用 6、虚引用 判断垃圾的条件 在Java虚拟机&#xff08;JVM&#xff09;中&#xff0c;垃圾收集器负责管理内存&#xff0c;其中的垃圾收集算法用于确定哪些对象是垃圾&#xff0c;可以被回收…

0002Java程序设计-springboot在线考试系统小程序

文章目录 **摘 要****目录**系统实现开发环境 编程技术交流、源码分享、模板分享、网课分享 企鹅&#x1f427;裙&#xff1a;776871563 摘 要 本毕业设计的内容是设计并且实现一个基于springboot的在线考试系统小程序。它是在Windows下&#xff0c;以MYSQL为数据库开发平台&…

记一次linux操作系统实验

前言 最近完成了一个需要修改和编译linux内核源码的操作系统实验&#xff0c;个人感觉这个实验还是比较有意思的。这次实验总共耗时4天&#xff0c;从对linux实现零基础&#xff0c;通过查阅资料和不断尝试&#xff0c;直到完成实验目标&#xff0c;在这过程中确实也收获颇丰&…

井盖位移监测系统怎么监测井盖位移

党的二十大报告提出&#xff0c;坚持人民城市人民建、人民城市为人民&#xff0c;提高城市规划、建设、治理水平。秉持依法治理、创新引领的理念&#xff0c;市政府应该坚定推进窨井盖安全管理工作&#xff0c;不断加大排查整治力度&#xff0c;弥补设施安全管理短板&#xff0…

每日一练:“打家劫舍“(House Robber)问题 II

有想要了解打家劫舍初级问题的&#xff0c;可以点击下面链接查看&#xff01; 每日一练&#xff1a;“打家劫舍“&#xff08;House Robber&#xff09;问题 I 1. 问题 假设有房屋形成一个环形&#xff0c;即第一个房屋和最后一个房屋也相邻&#xff0c;每个房屋里都存放着一定…

Java数组的复制、截取(内含例题:力扣-189.轮转数组)

目录 数组的复制、截取&#xff1a; 1、使用Arrays中的copyOf方法完成数组的拷贝 2、使用Arrays中的copyofRange方法完成数组的拷贝 题目链接&#xff1a; 数组的复制、截取&#xff1a; 1、使用Arrays中的copyOf方法完成数组的拷贝 public class Csdn {public static vo…

【Git】一文教你学会 submodule 的增、查、改、删

添加子模块 $ git submodule add <url> <path>url 为想要添加的子模块路径path 为子模块存放的本地路径 示例&#xff0c;添加 r-tinymaix 为子模块到主仓库 ./sdk/packages/online-packages/r-tinymaix 路径下&#xff0c;命令如下所示&#xff1a; $ git subm…

UI自动化测试神器:RunnerGo测试平台

可以直接进入官网下载开源版或点击右上角体验企业版体验 RunnerGo UI自动化平台 RunnerGo提供从API管理到API性能再到可视化的API自动化、UI自动化测试功能模块&#xff0c;覆盖了整个产品测试周期。 RunnerGo UI自动化基于Selenium浏览器自动化方案构建&#xff0c;内嵌高度…

可持续创新 精选路线

在加速企业数字化转型、 实现智能制造的升级之路上&#xff01; 使用好的工具固然重要&#xff0c; 而有好工具&#xff0c;也要会用工具。生信科技不仅为企业提供强大的产品支持&#xff0c; 更有全方位的定制化服务&#xff0c; 提升工程师的工具应用能力&#xff0c; 让企业…

海外https代理ip如何保障信息安全?该怎么选择?

海外https代理ip是指通信协议为https的海外真实网络地址ip&#xff0c;通常应用在各种跨境业务中。 一、什么是HTTPS协议 HTTP协议是一个应用层协议&#xff0c;通常运行在TCP协议之上。它是一个明文协议&#xff0c;客户端发起请求&#xff0c;服务端给出响应的响应。由于网…

pat实现基于邻接表表示的深度优先遍历[含非递归写法]

文章目录 1.递归2.非递归 1.递归 void DFS(ALGraph G, int v) {visited[v] 1;printf("%c ", G.vertices[v].data);for (ArcNode* cur G.vertices[v].firstarc; cur ! nullptr; cur cur->nextarc){if (!visited[cur->adjvex])DFS(G, cur->adjvex);} }2.非…

matlab画双坐标图的样式

matlab画双坐标图的样式 %% clc,clear,close all; t0:0.1:9*pi; figure; [AX,Ha,Hb]plotyy(t,sin(t),t,exp(t)); % 绘图并创建句柄 % ----------------- 设置刻度 set(AX(1),yTick,[-1.250:0.25:1.25]) % 设置左边Y轴的刻度 set(AX(2),yTick,[0:50:350]) …

2023年【危险化学品经营单位安全管理人员】考试内容及危险化学品经营单位安全管理人员最新解析

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 危险化学品经营单位安全管理人员考试内容是安全生产模拟考试一点通生成的&#xff0c;危险化学品经营单位安全管理人员证模拟考试题库是根据危险化学品经营单位安全管理人员最新版教材汇编出危险化学品经营单位安全管…

HarmonyOS开发:ArkTs常见数据类型

前言 无论是Android还是iOS开发&#xff0c;都提供了多种数据类型用于常见的业务开发&#xff0c;但在ArkTs中&#xff0c;数据类型就大有不同&#xff0c;比如int&#xff0c;float&#xff0c;double&#xff0c;long统一就是number类型&#xff0c;当然了也不存在char类型&…

新式的拉式膜片弹簧离合器设计机械设计CAD

wx供重浩&#xff1a;创享日记 对话框发送&#xff1a;离合器 获取完整论文报告工程源文件 减震弹簧 摩擦片 膜片弹簧 压盘 轴 扭转减震器 从动盘 离合器 离合器的结构设计 为了达到计划书所给的数据要求&#xff0c;设计时应根据车型的类别、使用要求、制造条件&#xff0c;…

Flink-简介与基础

Flink-简介与基础 一、Flink起源二、Flink数据处理模式1.批处理2.流处理3.Flink流批一体处理 三、Flink架构1.Flink集群2.Flink Program3.JobManager4.TaskManager 四、Flink应用程序五、Flink高级特性1.时间流&#xff08;Time&#xff09;和窗口&#xff08;Window&#xff0…

FreeRTOS深入教程(信号量源码分析)

文章目录 前言一.创建信号量二.释放信号量三.获取信号量成功获取获取不成功 总结 前言 本篇文章将为大家讲解信号量&#xff0c;源码分析。 在 FreeRTOS 中&#xff0c;信号量的实现基于队列。这种设计的思想是利用队列的特性来实现信号量&#xff0c;因为信号量可以被视为只…

借助 XEOS V6, 农牧龙头企业实现原有存储的高效在线替换

面对旧有存储系统的应用不足&#xff0c;某大型现代农牧龙头企业采用了星辰天合的对象存储 XEOS V6 方案&#xff0c; 该方案以其卓越的技术架构和同城双活异地灾备的解决方案完整性&#xff0c;在无缝高效完成系统替换的同时&#xff0c;可以极大地提升系统的灵活性和业务的连…

C/C++ 实现Socket交互式服务端

在 Windows 操作系统中&#xff0c;原生提供了强大的网络编程支持&#xff0c;允许开发者使用 Socket API 进行网络通信&#xff0c;通过 Socket API&#xff0c;开发者可以创建、连接、发送和接收数据&#xff0c;实现网络通信。本文将深入探讨如何通过调用原生网络 API 实现同…

RabbitMQ之发送者(生产者)可靠性

文章目录 前言一、生产者重试机制二、生产者确认机制实现生产者确认&#xff08;1&#xff09;定义ReturnCallback&#xff08;2&#xff09;定义ConfirmCallback 总结 前言 生产者重试机制、生产者确认机制。 一、生产者重试机制 问题&#xff1a;生产者发送消息时&#xff0…