0701从汇编的角度深入理解c++_多态演示

// 06C++TestBind.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

class Base{
public:
	int x;
	int y;
public:
	Base(){
		x=1;
		y=2;
	}
	virtual void Print(){

		printf("Base:%d,%d\n",x,y);
	}
};
class Sub1:public Base{
public:
	int A;
public:
	 Sub1(){
		x=4;
		y=5;
		A=6;
	}
	virtual void Print(){

		printf("Sub1:%d,%d,%d\n",x,y,A);
	}
	virtual void HHPrint(){

		printf("哈哈哈啊哈哈\n");
	}
	virtual ~Sub1(){
	}
};
class Sub2:public Base{
public:
	int B;
public:
	Sub2(){
		x=7;
		y=8;
		B=9;
	}
	virtual void Print(){

		printf("Sub2:%d,%d,%d\n",x,y,B);
	}
	virtual ~Sub2(){
	}
};


void testBind(Base* lp)
{
	lp->Print();    //查看反汇编
}

int _tmain(int argc, _TCHAR* argv[])
{
	
	//TestBind();
	
	getchar();
	return 0;
}

 根据IDA找到testBind的反汇编的位置:

.text:004113C0                 push    ebp
.text:004113C1                 mov     ebp, esp
.text:004113C3                 sub     esp, 0C0h
.text:004113C9                 push    ebx
.text:004113CA                 push    esi
.text:004113CB                 push    edi
.text:004113CC                 lea     edi, [ebp+var_C0]
.text:004113D2                 mov     ecx, 30h
.text:004113D7                 mov     eax, 0CCCCCCCCh
.text:004113DC                 rep stosd
.text:004113DE                 mov     eax, [ebp+lp]
.text:004113E1                 mov     edx, [eax]
.text:004113E3                 mov     esi, esp
.text:004113E5                 mov     ecx, [ebp+lp]
.text:004113E8                 mov     eax, [edx]
.text:004113EA                 call    eax
.text:004113EC                 cmp     esi, esp
.text:004113EE                 call    j___RTC_CheckEsp
.text:004113F3                 mov     esi, esp
.text:004113F5                 push    offset a11111   ; "11111\n"
.text:004113FA                 call    ds:__imp__printf
.text:00411400                 add     esp, 4
.text:00411403                 cmp     esi, esp
.text:00411405                 call    j___RTC_CheckEsp
.text:0041140A                 pop     edi
.text:0041140B                 pop     esi
.text:0041140C                 pop     ebx
.text:0041140D                 add     esp, 0C0h
.text:00411413                 cmp     ebp, esp
.text:00411415                 call    j___RTC_CheckEsp
.text:0041141A                 mov     esp, ebp
.text:0041141C                 pop     ebp
.text:0041141D                 retn

  在od中查看

 0x4113EA FF D0 call eax

目前是编译过,但是eax这个值是不确定的,eax是虚表里面存的第一个函数地址。

当没有继承的时候,就是Base里面的Print

当有继承的时候,就是子类里面的Print

这就是动态绑定(也叫多态)。

posted @ 2023-09-19 16:28  一日学一日功  阅读(23)  评论(0)    收藏  举报