C++系列-函数重载

函数重载

  • 函数数重载是指在同一作用域内,可以有一组相同函数名,不同参数列表的函数,这组函数被称为函数重载。
  • 重载函数通常用来命名一组功能相似的函数。
  • 编译器在函数调用时,会自动区分要调用哪一个函数。

函数重载的条件

  • 同一个作用域下
  • 函数名相同,函数参数不同
    – 参数个数不同
    – 参数顺序不同
    – 参数类型不同
  • const/volatiles 属性不同
  • 不可以使用返回值作为重载的条件

参数不同

code:
#include<iostream>
using namespace std;
void test()
{
	cout << "void test()" << endl;
}
void test(int a)
{
	cout << "void test(int a)" << endl;
}
void test(int a, float b)
{
	cout << "void test(int a, float b)" << endl;
}
void test(float a, int b)
{
	cout << "void test(float a, int b)" << endl;
}
void main()
{
	test();
	test(100);
	test(100, 3.14);
	test(3.14, 100);
	system("pause");
}
	
result:
void test()
void test(int a)
void test(int a, float b)
void test(float a, int b)

const/volatiles 属性不同

code:
#include <iostream>
using namespace std;
struct foo 
{
	void bar() const //第一个重载函数
	{ 
		cout << "int bar() const" << endl;
	}; 
	void bar()		//第二个重载函数
	{ 
		cout << "int bar()" << endl;
	}; 
};
int main()
{
	const foo a;
	a.bar();
	foo b;
	b.bar();
	system("pause");
	return 0;
}

result:
int bar() const
int bar()

函数重载注意事项

引用作为重载

  • 引用也可以作为重载,参数可以分为const和非const,可以作为重载条件。
 code:
#include<iostream>
using namespace std;
void test(int& a)
{
	cout << "void test(int &a)" << endl;
}
void test(const int& a)
{
	cout << "void test(const int& a)" << endl;
}
void main()
{
	int a = 10;
	test(a);
	test(10);		// 当执行void test(int &a) 则为int &a=10,会出错,const int& a=10,正常
	system("pause");
}

result:
void test(int &a)
void test(const int& a)

函数重载遇到默认参数

  • 如果有二义性存在,则会报错。
code:
#include<iostream>
using namespace std;

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

void main()
{
	//test(666);		// 报错,不知道执行哪一个
	test(20, 30);
	system("pause");
}

result:
	void test(int a, int b = 10)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值