C++重载函数

1,重载函数

     重载函数是函数的一种特殊情况,为方便使用,C++允许在同一范围中声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同,也就是说用同一个运算符完成不同的运算功能。这就是重载函数。重载函数常用来实现功能类似而所处理的数据类型不同的问题。但是重载函数的返回值类型可以不同。例子如下:

#include<iostream>
#include<string>
using namespace std;
void show(const int a)
{
	cout << "A:" << a <<endl; 
}
void show()
{
	cout << "Hello World!" << endl;
}
void show(const string s)
{
	cout << s << endl;
}
int main()
{
	string s("ASIA");
	int a = 1;
	show(a);
	show(s);
	show();
	return 0;
} 

两个重载函数必须在下列一个或两个方面有所区别:
1、函数有不同参数。
2、函数有不同参数类型。
2,重载函数的注意事项

(1)函数屏蔽(隐藏函数)

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

void show(int a);
void show(double b);
void show(string s);
void print(string s,int a)
{
        show(a);
	show(s);
	show(3.14);
}

int main()
{
	string s("ASIA");
	int a = 1;
        print(s,a);
	return 0;
} 
void show(const int a)
{
	cout << "A:" << a <<endl; 
}
void show(double b)
{
	cout << b << endl;
}
void show(const string s)
{
	cout << s << endl;
}

假如修改为如下:

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

void show(int a);
void show(double b);
void show(string s);
void print(string s,int a)
{
	void show(int a);
        show(a);
//	show(s);
	show(3.14);
}

int main()
{
	string s("ASIA");
	int a = 1;
        print(s,a);
	return 0;
} 
void show(const int a)
{
	cout << "A:" << a <<endl; 
}
void show(double b)
{
	cout << b << endl;
}
void show(const string s)
{
	cout << s << endl;
}


(2)变量屏蔽

#include<iostream>

using namespace std;

void show(int a)
{
	cout << "Hello world" << endl;
}
void print(int a)
{
//	int show = 1;
        show(a);

}
int main()
{
	int a = 1;
        print(a);
	return 0;
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值