C++函数重载

函数重载概述

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

函数重载条件

  • 同一作用域
  • 函数名相同,函数返回值类型相同
  • 函数参数列表不完全相同!!!(参数类型,个数,顺序)

 总结,函数重载需在同一作用域下,只有函数参数列表不完全相同!!!

#include <iostream>
using namespace std;

void fun(int a){
	cout << "fun(int a)" << endl;
}

//函数返回值类型不同不能作为函数重载条件
//int fun(int a){
//	cout << "fun(int a)" << endl;
//	return 0;
//}

void fun(int a, int b){
	cout << "fun(int a, int b)" << endl;
}


void fun(int a, double b){
	cout << "fun(int a, double b)" << endl;
}

void fun(double b, int a){
	cout << "fun(int a, double b)" << endl;
}

int main() {
	fun(10);
	fun(10, 20);
	fun(10, 20.0);
	fun(20.0, 10);
	return 0;
}

 函数重载注意事项

引用作为重载条件

#include <iostream>
using namespace std;

void fun(int &a){    //变量的引用
	cout << "fun(int &a)" << endl;
}

void fun(const int &a){    //常量的引用
	cout << "fun(const int &a)" << endl;
}

int main() {
	int a = 20;
	fun(a);    //a为变量,优先走fun(int &a), 此处是变量的引用
	fun(10);    //10为常量,优先走fun(const int &a),此处是常量的引用
	return 0;
}

当我们执行fun(10)时,参事10无法传递给fun(int &a),因为int &a = 10是违法的。参数10只能传递给fun(const int &a),因为const int &a 会做以下步骤:

int temp = 10;
const int &a = temp;

 

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

#include <iostream>
using namespace std;

void fun(int a){
	cout << "fun(int a)" << endl;
}

void fun(int a, int b = 10){
	cout << "fun(int a, int b = 10)" << endl;
}

int main() {
	fun(10);    //错误
	return 0;
}

如果不调用fun(10)程序不会出错。

如果调用,上面定义的两个函数均可使用,便会出现二义性,报错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起风了呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值