目录
函数重载是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;
}
注意:函数重载时避免使用默认参数。