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

结果:

相关推荐
凯瑟琳.奥古斯特41 分钟前
力扣1235:加权区间调度最优解
java·python·算法·leetcode·职场和发展
_童年的回忆_1 小时前
【php】在linux下PHP安装amqp扩展
linux·开发语言·php
耶叶1 小时前
餐厅出入最少人数问题:贪心算法
算法·贪心算法
gihigo19981 小时前
基于小波框架与稀疏表示的SAR图像目标识别系统(MATLAB实现)
算法
AIMath~1 小时前
python中的uv命令揭秘
开发语言·python·uv
弹简特1 小时前
【零基础学Python】06-Python模块和包、异常处理、文件常用操作
开发语言·python
x***r1511 小时前
Postman-win64-7.2.2-Setup安装步骤详解(附API接口测试与参数配置教程)
开发语言·lua
吴可可1231 小时前
CAD2004自定义实体开发环境配置
c++·算法
装不满的克莱因瓶1 小时前
矩阵的主成分是什么?主成分分析(PCA)又能做什么?
人工智能·线性代数·算法·机器学习·ai·矩阵·pca
念恒123061 小时前
Python 面向对象编程核心:对象、实例化、封装与变量作用域
开发语言·python