栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++快速入门第三篇(函数重载与缺省参数)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++快速入门第三篇(函数重载与缺省参数)

注意:阅读本专栏博客之前一定要有C语言基础. 如何学习:看懂此博客里的代码段即可 有条件的同学我建议复制下来编译一下(vs2013-vs2022)

每一篇博客我都会修改很多次,同学们可以放心浏览.

C++函数内联:
//NO.1 函数内联:以二进制形式存在
//1.1 内联函数的特点:短小精悍(编译速度快)
//1.2 inline 修饰
//1.3 如果在结构体中或者类中实现的函数默认为内联函数
#include 
using namespace std;

inline int Max(int a, int b) {
	return a > b ? a : b;
}

int main() {

	int max = Max(1, 2);
	cout << max << endl;

	while (1);
	return 0;
}
C++函数重载:

函数重载代码段:
//No.2 函数重载:在同一个名字空间下,允许同名不同参的函数存在
#include 
using namespace std;

//2.1 参数个数不同
void print(int a, int b)
{
	cout << a + b << endl;
}
void print(int a)
{
	cout << a << endl;
}
//2.2 参数的类型不同
void print(int a, char b)
{
	cout << a + b << endl;
}
//3.3 参数的顺序不同:一定是存在不同的类型的基础之上
void print(char a, int b)
{
	cout << a + b << endl;
}

#if 0

void print(int b, int a) {	
	cout << a + b << endl;	
}
#endif

int main() {

	print(1, 2);
	print(1);
	print('A', 2);
	print(1, 'A');

	while (1);
	return 0;
}
C++函数缺省参数:

#include 
using namespace std;

//No.3 函数缺省: 就是给函数参数初始化
//注意: 缺省的顺序只能从右往左连续性的缺省
//       多文件中 只需要在.h声明缺省
int sum(int a = 0, int b = 0, int c = 0, int d = 0)
{
	return a + b + c + d;
}

int main() {

	cout << sum(11, 22, 33, 44) << endl;
	cout << sum() << endl;
	cout << sum(1) << endl;
	cout << sum(1, 2) << endl;
	cout << sum(1, 2, 3) << endl;
	cout << sum(1, 2, 3, 4) << endl;

	while (1);
	return 0;
}
 这个函数重载的例子可以看一下

#include 
using namespace std;

void print(int * arr, int len = 10, bool isAfter = false);

void print(int* arr){
	printf("重载的printn");
}

void sort(int* arr, int len){
	for (int i = 0; i < len; i++){
		for (int j = 0; j < len - i - 1; j++){
			int temp;
			if (arr[j]>arr[j + 1]){
				temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}


int main()
{
	int arr[10] = { 1, 2, 5, 6, 9, 0, 8, 7, 4, 3 };

	print(arr, 10);
	sort(arr, 10);
	print(arr, 10, true);


	while (1);
	return 0;
}

void print(int* arr, int len, bool isAfter){
	if (isAfter){
		printf("After  sort:");
	}
	else{
		printf("Before sort:");
	}

	for (int i = 0; i < len; i++) printf("%d ", arr[i]);
	printf("n");
}

下一篇写C++结构体 + String

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/849337.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号