【C++】函数重载

1、函数重载概述

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

函数重载满足条件:

(1)同一个作用域(我们现在写的函数都是全局函数,都在全局作用域中)

(2)函数名称相同

(3)函数参数类型不同或者参数个数不同或者顺序不同

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

示例:

参数个数不同

cpp 复制代码
#include<iostream>
using namespace std;
void func()
{
	cout << "func的调用" << endl;
}
void func(int a)
{
	cout << "func(int a) 的调用" << endl;
}
int main()
{
	func();
	func(100);
	system("pause");
	return 0;
}

结果:

参数类型不同:

cpp 复制代码
#include<iostream>
using namespace std;
void func(int a)
{
	cout << "func(int a) 的调用" << endl;
}
void func(double a)
{
	cout << "func(double a) 的调用" << endl;
}
int main()
{ 
	func(10);
	func(1.2);
	system("pause");
	return 0;
}

结果:

参数顺序不同:

cpp 复制代码
#include<iostream>
using namespace std;
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(10, 2.1);
	func(2.1, 10);

	system("pause");
	return 0;
}

结果:

2、函数重载注意事项

(1)引用作为重载条件

示例:

cpp 复制代码
#include<iostream>
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(int &a),
	func(10);//调用func(const int &a)

	system("pause");
	return 0;
}

结果:

(2)函数重载碰到默认参数

示例:

cpp 复制代码
#include<iostream>
using namespace std;
void func(int a, int b = 10)
{
	cout << "func(int a,int b=10)的调用" << endl;
}
void func(int a)
{
	cout << "func(int a)的调用" << endl;
}
int main()
{
	
	func(10, 20);
	system("pause");
	return 0;
}

结果:

相关推荐
Niuguangshuo6 小时前
论文解读:CTC,端到端序列识别的开山之作
算法·语音识别
讳疾忌医丶6 小时前
深度拆解 RocksDB 内核:基于 C++17 的 FIFO 调度状态机与温度阶梯自愈设计
java·c++·算法·架构
lsswear6 小时前
Python 并发 线程
开发语言·python
2401_868534786 小时前
OpenStack 架构全景:八个核心组件深度拆解
c++·需求分析
郑州光合科技余经理6 小时前
国际版外卖系统:税率字段怎么和订单主流程解耦
android·java·开发语言·前端·后端·php·ai编程
高亦真6 小时前
今天是学习嵌入式的第37天
linux·学习·算法
软件课代表CiCi7 小时前
运行库是什么?电脑缺运行库怎么办?c++运行库缺失修复全攻略
开发语言·c++·windows·电脑·dll修复·dll丢失·运行库
Ivanqhz7 小时前
MLIR OpBuilder
开发语言·python·mlir
蒸蒸yyyyzwd8 小时前
从面经中学到的三件事
c++·笔记
时时三省8 小时前
【时时三省】计算机c语言二级考试选择题重点
c++