C++:函数进阶

目录

一、函数的默认参数

二、占位参数

三、函数重载

1.基本使用

2.引用作为函数重载的条件

3.函数重载碰到默认参数


一、函数的默认参数

概念:在C++中可以在函数的参数列表中为参数设置默认值

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

注意事项:

  • 如果某个参数有默认值,那从左往后的参数都必须要有参数值。
int function(int a, int b = 10, int c) {
	return a + b + c;
}
  • 如果函数的声明有默认值,函数的实现就不能有默认参数。(编译器不知道按哪个运行)
int function(int a, int b = 10, int c = 20);
int function(int a, int b = 10, int c = 20) {
	return a + b + c;
}

使用示例:

#include <iostream>
using namespace std;

int function(int a, int b = 10, int c = 20) {
	return a + b + c;
}


int main() {

	cout << function(1) << endl;//补满未设置初始值的参数
	cout << function(1, 2) << endl;//若传入参数则初始值会被替代

	system("pause");
	return 0;
}

二、占位参数

作用:在形参列表用于占位,当要调用函数时必须要填补该位置。了解即可。

void function(int) {
	cout << "123" << endl;
}

三、函数重载

1.基本使用

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

满足条件:

  • 同一个作用域下(比如全局作用域)
  • 函数名相同
  • 函数参数类型不同个数不同顺序不同
void function() {
	cout << "1" << endl;
}

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

void function(int a,int b) {
	cout << "3" << endl;
}

void function(int b, int a) {
	cout << "4" << endl;
}

void function(double a) {
	cout << "5" << endl;
}

注意:函数返回值的不同不可作为函数重载的条件。

2.引用作为函数重载的条件

引用作为函数重载有两种方式:

#include <iostream>
using namespace std;

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

void function(const int& a) {
	cout << "function(const int& a)" << endl;
}



int main() {

	int a = 10;
	function(a);//变量属于可读可写的状态,默认使用第一个
	function(10);//使用涉及到常量引用的内容

	system("pause");
	return 0;
}

3.函数重载碰到默认参数

当加入默认参数时,调用函数系统可能存在不知道调用其中的哪一个参数,如下操作中使用function(a);调用会出错。尽量避免函数重载与默认参数的混合使用。

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

void function(int a,int b = 10) {
	cout << "function(int a,int b = 10)" << endl;
}

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值