C++函数重载

目录

1,函数重载的条件

2,引用作为重载的条件

3,重载碰到默认参数


函数重载是C++静态多态的一种形式。 

1,函数重载的条件

(1)函数作用域相同;

(2)函数名相同;

(3)函数参数个数不同,或参数类型不同,或参数顺序不同;

注意:函数返回值类型不能作为重载的条件。

#include <iostream>
using namespace std;
#include <string>

void func()
{
	cout << "func()函数调用" << endl;
}

void func(int a)
{
	cout << "func(int a)函数调用" << endl;
}

void func(double a)
{
	cout << "func(double a)函数调用" << endl;
}

void func(int a,float b)
{
	cout << "func(int a,float b)函数调用" << endl;
}

void func(float a, int b)
{
	cout << "func(float a, int b)函数调用" << endl;
}

int main()
{
	func();
	func(10);
	func(3.14);
	func(10, 3.14);
	func(3.14,10);

	system("pause");
	return 0;
}

运行结果:

func()函数调用
func(int a)函数调用
func(double a)函数调用
func(int a,float b)函数调用
func(float a, int b)函数调用
请按任意键继续. . .

2,引用作为重载的条件

#include <iostream>
using namespace std;
#include <string>

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(10);

	system("pause");
	return 0;
}

 运行结果:

func(int& a)函数调用
func(const int& a)函数调用
请按任意键继续. . .

3,重载碰到默认参数

#include <iostream>
using namespace std;
#include <string>

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);此命令会报错,编译器不知道运行func(int a,int b=10)还是func(int a)

	func(10, 10);//会运行func(int a,int b=10)

	system("pause");
	return 0;
}

注意:函数重载时避免使用默认参数。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值