前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >函数重载

函数重载

作者头像
大忽悠爱学习
发布2021-03-02 15:06:19
5560
发布2021-03-02 15:06:19
举报
文章被收录于专栏:c++与qt学习

基本语法

作用:

  1. 函数名可以相同,提高复用性

函数重载满足条件:

  1. 同一个作用域下
  2. 函数名称相同
  3. 函数参数类型不同,或者个数不同,或者顺序不同 (1)函数参数类型不同
代码语言:javascript
复制
#include<iostream>
using namespace std;
//函数重载
//1.作用域:当前测试函数都在全局作用域下
//2.函数名称都相同
//3.(1)函数参数类型不同
void test()
{
	cout << "test函数调用" << endl;
}
void test(int a)
{
	cout << "test 的 int a 函数调用" << endl;
}
void test(double a)
{
	cout << "test 的 double a 函数调用" << endl;
}
int main()
{
	test();
	test(10);
	test(3.14);
	system("pause");
	return 0;
}
在这里插入图片描述
在这里插入图片描述

(2)个数不同

代码语言:javascript
复制
#include<iostream>
using namespace std;
//函数重载
//1.作用域:当前测试函数都在全局作用域下
//2.函数名称都相同
//3.(1)个数不同
void test()
{
	cout << "test函数调用" << endl;
}
void test(int a)
{
	cout << "test 的 int a 函数调用" << endl;
}
void test(int a,int b)
{
	cout << "test 的 int a int b 函数调用" << endl;
}
int main()
{
	test();
	test(10);
	test(10, 20);
	system("pause");
	return 0;
}
在这里插入图片描述
在这里插入图片描述

(3)顺序不同

代码语言:javascript
复制
#include<iostream>
using namespace std;
//函数重载
//1.作用域:当前测试函数都在全局作用域下
//2.函数名称都相同
//3.(1)顺序不同
void test(double a,int b)
{
	cout << "test 的double a int b 函数调用" << endl;
}
void test(int a,double b)
{
	cout << "test 的 int a double b 函数调用" << endl;
}
int main()
{
	test(3.14, 2);
	test(2, 3.14);
	system("pause");
	return 0;
}
在这里插入图片描述
在这里插入图片描述

注意:

  1. 函数返回值不可以作为函数重载的条件
在这里插入图片描述
在这里插入图片描述

注意事项

注意const不能作为int等数据类型的重载条件

在这里插入图片描述
在这里插入图片描述

1. const引用作为函数重载条件

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

10是常量所以只能被有const引用的函数调用,变量b既可以被const引用函数调用,也可以被普通引用调用,但普通引用优先级高于const引用,所以优先被普通引用调用

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

注意:const int &a=10 是编译器自动优化为:int temp=10;int& a=temp;

const 的引用既可以指向常量也可以指向变量,但指向的值不可以修改

2.函数重载碰到默认参数

会出现二义性,尽量避免出现这种情况

在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/02/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基本语法
  • 注意事项
  • 1. const引用作为函数重载条件
  • 注意:const int &a=10 是编译器自动优化为:int temp=10;int& a=temp;
  • const 的引用既可以指向常量也可以指向变量,但指向的值不可以修改
  • 2.函数重载碰到默认参数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档