C++中函数名称可以重复
- 必须在同一个作用域,函数名称相同
void func() {
cout << "无参数的func" << endl;
}
class Person {
void func();
};
- 函数参数的个数不同
void func() {
cout << "无参数的func" << endl;
}
void func(double a) {
cout << "有参数的func(double a)" << endl;
}
void func(double a,int b) {
cout << "有参数的func(double a,int b)" << endl;
}
- 或类型不同
void func(int a) {
cout << "有参数的func(int a)" << endl;
}
void func(double a) {
cout << "有参数的func(double a)" << endl;
}
- 或顺序不同
void func(double a,int b) {
cout << "有参数的func(double a,int b)" << endl;
}
void func(int a, double b) {
cout << "有参数的func(int a,double b)" << endl;
}
返回值可以作为函数重载的条件吗??? 不可以
当函数重载碰到了默认参数时候,要注意避免二义性问题
- 引用的重载版本
引用必须要引合法的内存空间
void func3(const int &a) { //int tmp = 10 ; const int &a = tmp;
cout << "const int &a" << endl;
}
void func3(int &a) {
cout << "int &a" << endl;
}
void test03() {
int a = 10;
func3(a);
func3(37);//const也可以作为重载的条件
}