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

结果:

相关推荐
夜晚中的人海4 分钟前
【C++】智能指针介绍
android·java·c++
yacolex10 分钟前
3.3_数据结构和算法复习-栈
数据结构·算法
小蕾Java14 分钟前
Python详细安装教程(附PyCharm使用)
开发语言·python·pycharm
weixin_3077791321 分钟前
AWS云上ClickHouse数据仓库部署方案详解
开发语言·clickhouse·自动化·云计算·aws
weixin_3077791323 分钟前
使用AWS IAM和Python自动化权限策略分析与导出
开发语言·python·自动化·云计算·aws
惜月_treasure29 分钟前
从零构建私域知识库问答机器人:Python 全栈实战(附完整源码)
开发语言·python·机器人
茉莉玫瑰花茶37 分钟前
动态规划 - 两个数组的 dp 问题
算法·动态规划
mark-puls44 分钟前
Qt界面布局利器:QStackedWidget详细用法解析
开发语言·qt
微笑尅乐1 小时前
从暴力到滑动窗口全解析——力扣8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
火花怪怪1 小时前
LaMer结晶动力学模型
算法