从零起步学C++笔记(五)-函数

1 函数进阶

1.1 函数的默认参数

返回值类型 函数名 (形参 = 默认值){}

如果我们向函数中传入了数据,就使用传入的数据

如果没有传入数据,就使用默认值

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

int func(int a, int b = 20, int c = 30) {
	return a + b * c;
}

int main() {
	cout << func(4,0);
	return 0;
}

注意: 如果某个参数有默认值,那么这个参数右边的参数也需要有默认值;

//这种是错误的
int func(int a, int b = 20, int c ) {
	return a + b * c;
}

注意: 如果函数声明有默认参数,那么函数实现就不写默认参数,声明和实现只能有一处有默认参数

以下是错误的

//声明
int func(int a, int b = 20, int c = 30);

//实现
int func(int a, int b = 20, int c = 30) {
	return a + b * c;
}

1.2 函数占位参数

形参列表里可以有占位参数,调用时需要填补该位置

返回类型 函数名(数据类型){}

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

void func(int) {
	cout << "hello world!";
}

int main() {
	func(1);
	return 0;
}

占位参数也可以有默认参数

1.3 函数重载

1.3.1 函数重载概述

作用:函数名可以相同,提高复用性

函数重载满足条件

  • 同一个作用域
  • 函数名相同
  • 函数参数类型不同或者个数不同或者顺序不同

注意: 返回值不可以作为重载的条件

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

void func() {
	cout << "hello world!";
}

void func(int a) {
	cout << "hello world!";
}

int main() {
	func();
	func(1);
	return 0;
}

1.3.2 函数重载注意事项

  • 引用作为函数重载的条件
#include<iostream>
#include<string>
using namespace std;

void func(int& a) {
	cout << "func(int& a)被调用" << endl;
}

void func(const int& a) {
	cout << "func(const int& a)被调用" << endl;
}

int main() {
	int a = 10;
	func(a);
	func(10);//int& a=10;不合法// const int& a=10 he合法 
	return 0;
}
  • 函数重载碰到默认参数
#include<iostream>
#include<string>
using namespace std;

void func(int a) {
	cout << "func(int a)" << endl;
}

void func(int a,int b=10) {//有默认参数
	cout << "func(int a,int b)" << endl;
}

int main() {
	int a = 10;
	int b = 20;
	//func(a);//这句会报错
	func(a,b);
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值