函数重载
- 函数数重载是指在同一作用域内,可以有一组相同函数名,不同参数列表的函数,这组函数被称为函数重载。
- 重载函数通常用来命名一组功能相似的函数。
- 编译器在函数调用时,会自动区分要调用哪一个函数。
函数重载的条件
- 同一个作用域下
- 函数名相同,函数参数不同
– 参数个数不同
– 参数顺序不同
– 参数类型不同 - 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);
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(20, 30);
system("pause");
}
result:
void test(int a, int b = 10)