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;
}