C++函数提高篇(默认参数,占位参数,函数重载)

函数默认参数

C++函数中的形参列表中的形参是可以有默认值的

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

注意事项:

  1. 如果我们自己传入数据,就用自己的数据,如果没有,就用默认值
  2. 如果某个位置参数有默认值,那么从这个位置往后,从左往右,必须都要有默认值
  3. 如果函数声明有默认参数,函数实现就不能有默认参数,声明和实现只能有一个有默认参数
#include<iostream>
using namespace std;

//函数默认参数
//如果我们传入数据,则会使用我们自己的数据
//如果没有传入数据,则会使用默认值
//注意事项:从第一个默认值位置开始往后,从左到右都必须有默认值
//          如果函数声明有默认值,函数实现就不能有默认值
int test(int a,int b = 1,int c = 2)
{
	return a + b + c;
}

int main()
{

	cout << "a+b+c = " << test(10,20,30) << endl;

	system("pause");
	return 0;
}

a+b+c = 60

函数占位参数

C++函数中的形参列表里可以有占位参数,用来占位,调用函数时必须填补此位置

语法:返回值类型 函数名(数据类型){ }

#include<iostream>
using namespace std;

//占位参数
//占位参数还可以有默认值
void test(int a,int = 10)
{
	cout << "this is test" << endl;
}

int main()
{
	test(10,20);

	system("pause");
	return 0;
}

this is test

函数重载概述

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

函数重载满足条件:

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

注意:函数返回值不可以做为函数重载的条件 即结构体前面所写的返回值类型

#include<iostream>
using namespace std;

//函数重载
//函数重载满足条件
// 1、同一个作用域下
// 2、函数名称相同
// 3、函数参数 类型不同或者个数不同或者顺序不同
//函数参数 
void test()
{
	cout << "test的调用" << endl;
}

void test(int a)
{
	cout << "test(int a)的调用" << endl;
}

void test(double a)
{
	cout << "test(double a)的调用" << endl;
}

void test(int a,double b)
{
	cout << "test(int a,double b)的调用" << endl;
}

int main()
{
	test();
	test(10);
	test(3.14);
	test(10, 3.14);

	system("pause");
	return 0;
}

test的调用
test(int a)的调用
test(double a)的调用
test(int a,double b)的调用

函数重载注意事项

  • 引用作为重载条件
  • 函数重载碰到函数默认值
#include<iostream>
using namespace std;

//函数重载的注意事项
//1、引用作为重载条件
void test(int &a)       //int &a = 10 不合法
{
	cout << "test的调用" << endl;
}

void test(const int &a) //const int & = 10 合法
{
	cout << "test(const int &a)的调用" << endl;
}

//2、数重载碰到函数默认值 
void test1(int a,int b = 10)
{
	cout << "test1的调用" << endl;
}
void test1(int a)
{
	cout << "test1(int a)的调用" << endl;
}
int main()
{
	int a = 10;
	test(a);
	test(10);
    //test1(10) //当函数重载碰到默认参数,出现二义性,报错,尽量避免这种情况
	test1(10, 20);
	system("pause");
	return 0;
}

test的调用
test(const int &a)的调用
test1的调用

碰到默认参数,容易产生歧义,即传入一个数据时能运行多个函数,所以我们需要避免这种情况

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魏大橙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值