c++学习(第8天)---函数(黑马程序员学习笔记)

本文介绍了C++中的函数默认参数、占位参数及函数重载的概念和使用方法。通过示例代码展示了如何定义和调用带有默认参数的函数,如何使用函数占位符以及如何实现函数重载来实现不同功能的同名函数。理解这些概念对于提升C++编程能力至关重要。
摘要由CSDN通过智能技术生成

1.函数默认参数

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

语法:
返回值类型 函数名 (参数= 默认值){}
#include<iostream>
using namespace std;
//定义默认3个参数函数
	int func1(int a=10, int b = 10, int c = 10) 
	{
		return a + b + c;
	}
	//定义默认2个参数函数
	int func2(int a, int b = 10, int c = 10)
	{
		return a + b + c;
	}
	//定义默认1个参数函数
	int func3(int a, int b, int c = 10)
	{
		return a + b + c;
	}
	int main()
	{

		cout << "ret = " << func1() << endl;
		cout << "ret = " << func2(5) << endl;
		cout << "ret = " << func3(5,6) << endl;
		
		system("pause");

		return 0;
	}

在这里插入图片描述
总之:如果没有传入实参,就采用默认的形参,如果我们传入实参,就采用我们传入的实参。

2.函数中的占位参数

语法: 返回值类型 函数名 (数据类型){}
#include<iostream>
using namespace std;
//定义默认3个参数函数
void func(int)
{
	cout << "函数占位符" << endl;
}
void func1(int, int)
{
	cout << "函数占位符" << endl;
}
	int main()
	{
		func(10);
		func(1010);
		system("pause");

		return 0;
	}

3.函数重载

作用:函数名可以相同

函数重载满足条件:

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

#include<iostream>
using namespace std;

//函数重载需要函数都在同一个作用域下
void func()
{
	cout << "func 的调用!" << endl;
}
void func(int a)
{
	cout << "func (int a) 的调用!" << endl;
}
void func(double a)
{
	cout << "func (double a)的调用!" << endl;
}
void func(int a, double b)
{
	cout << "func (int a ,double b) 的调用!" << endl;
}
void func(double a, int b)
{
	cout << "func (double a ,int b)的调用!" << endl;
}
int main() {

	func();
	func(10);
	func(3.14);
	func(10, 3.14);
	func(3.14, 10);

	system("pause");

	return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值