大家都知道 C++(www.cppentry.com) 等面向对象的语言支持函数重载,C++(www.cppentry.com) 实现函数重载很大程度上依赖与编译器对函数名的 Mangling(损坏,破坏),即 C++(www.cppentry.com) 的源代码被编译后同名的重载函数名字会被破坏,一般是在原函数名前后加上特定的字符串,以区分不同重载函数,然后在调用的时候根据参数的不同选择合适的函数,如下代码说明了编译器是如何处理普通函数重载的:
#include <iostream>
usingnamespacestd;
intfunc(void)
{
cout<<"func without parameters"<<endl;
}
intfunc(intia)
{
cout<<"func with one int parameter:"<<endl;
cout<< ia <<endl;
}
intfunc(intia,floatfb)
{
cout<<"func with one int parameter and one float parameter"<<endl;
cout<< ia <<endl;
cout<< fb <<endl;
}
intmain()
{
func();
func(5);
func(5,5.0);
}
g++ -S ./t.cc
编译后生成汇编代码可能如下:
.file"t.cc"
.local _ZStL8__ioinit
.comm _ZStL8__ioinit,1,1
.section .rodata
.LC0:
.string"func without parameters"
.text
.globl _Z4funcv
.type _Z4funcv, @function
_Z4funcv:
.LFB966:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset8
.cfi_offset5, -8
movl %esp, %ebp
.cfi_def_cfa_register5
subl $24, %esp
movl $.LC0,4(%esp)
movl $_ZSt4cout, (%esp)
call_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
movl $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_,4(%esp)
movl %eax, (%esp)
call_ZNSolsEPFRSoS_E
leave
.cfi_restore5
.cfi_def_cfa4,4
ret
.cfi_endproc
.LFE966:
.size _Z4funcv, .-_Z4funcv
.section .rodata
.LC1:
.string"func with one int parameter"
.text
.globl _Z4funci
.type _Z4funci, @function
_Z4funci:
.LFB967:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset8
.cfi_offset5, -8
movl %esp, %ebp
.cfi_def_cfa_register5
subl $24, %esp
movl $.LC1,4(%esp)
movl $_ZSt4cout, (%esp)
call_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
movl8(%ebp), %edx
movl %edx,4(%esp)
movl %eax, (%esp)
call_ZNSolsEi
movl $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_,4(%esp)
movl %eax, (%esp)
call_ZNSolsEPFRSoS_E
leave
.cfi_restore5
.cfi_def_cfa4,4
ret
.cfi_endproc
.LFE967:
.size _Z4funci, .-_Z4funci
.section .rodata
.align4
.LC2:
.string"func with one int parameter and one float parameter"
.text
.globl _Z4funcif
.type _Z4funcif, @function
_Z4funcif:
.LFB968:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset8
.cfi_offset5, -8
movl %esp, %ebp
.cfi_def_cfa_register5
subl $24, %esp
movl $.LC2,4(%esp)
movl $_ZSt4cout, (%esp)
call_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
movl $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_,4(%esp)
movl %eax, (%esp)
call_ZNSolsEPFRSoS_E
movl8(%ebp), %eax
movl %eax,4(%esp)
movl $_ZSt4cout, (%esp)
call_ZNSolsEi
movl $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_,4(%esp)
movl %eax, (%esp)
call_ZNSolsEPFRSoS_E
movl12(%ebp), %eax
movl %eax,4(%esp)
movl $_ZSt4cout, (%esp)
call_ZNSolsEf
movl $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_,4(%esp)
movl %eax, (%esp)
call_ZNSolsEPFRSoS_E
leave
.cfi_restore5
.cfi_def_cfa4,4
ret
.cfi_endproc
.LFE968:
.size _Z4funcif, .-_Z4funcif
.globl main
.type main, @function
main:
.LFB969: