C++函数重载
1.函数重载的规则
-
函数名相同
-
参数列表不同
- 参数类型不同
- 参数个数不同
2.注意
返回值类型与函数重载无关。
调用函数时,实参的隐式类型转换可能产生二义性。
如下:
以下为错误代码:
代码中重载的方法为test(long a)和test(double a)方法,在main()方法中调用test(10),编译无法通过,因为10可以隐式的转换为 long类型的10L和double类型的10.0,所以程序产生了二义性,无法将方法重载。
#include<iostream>
using namespace std;
void test(double a){
cout << "test(double a)" << a << endl;
}
void test(long a){
cout << "test(long a)" << a << endl;
}
int main(){
test(10);
return 0;
}
编译结果:
修正后的代码:
为了防止代码的二义性,为int类型的参数也重载一个方法。
#include<iostream>
using namespace std;
void test(int a){
cout << "test(int a)" << a << endl;
}
void test(double a){
cout << "test(double a)" << a << endl;
}
void test(long a){
cout << "test(long a)" << a << endl;
}
int main(){
test(10);
return 0;
}
编译运行结果:
3.函数重载的本质
1. name mangling(name decoration)技术
使用了name mangling的技术。
-
c++编译器默认会对符号名经行改编,修饰,比如函数重载,编写时函数名是一样的,但是编译过后,会被改编修饰。
-
不同的编译器(MSVC,g++)会有不同的生成规则。
2.使用VS2019和IDA反汇编证明
编译时,使用Release模式,并且关闭编译器优化。
将编译好的.exe文件放入IDA里边经行反汇编,得到如图所示:
我们可以看到,原来的main函数的名字被改变成为_main,3个test方法也被同样的方式经行的修饰改编。