【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;
}

结果:

相关推荐
脏脏a12 分钟前
C 语言分支与循环:构建程序逻辑的基石
c语言·开发语言
西猫雷婶15 分钟前
python学智能算法(七)|KNN邻近算法
算法
用户90803219692520 分钟前
OpenCV三大经典项目实战 掌握计算机视觉核心技能-|果fx
算法
caoruipeng23 分钟前
Windows编程----结束进程
c++·windows·子进程
Vitalia27 分钟前
⭐算法OJ⭐经典题目分类索引(持续更新)
算法
Alchemist0128 分钟前
算法笔记
算法
结衣结衣.36 分钟前
【Qt】带参数的信号和槽函数
开发语言·qt·c++11
冷琴199638 分钟前
基于Python+Vue开发的电影订票管理系统源码+运行步骤
开发语言·vue.js·python
L Jiawen39 分钟前
【Python 2D绘图】Matplotlib绘图(统计图表)
开发语言·python·matplotlib
请来次降维打击!!!1 小时前
算法优选系列(1.双指针_下)
c++·算法