用派生类的指针调用基类的函数为什么也可以实现多态?
#include<iostream.h>class A{ public: virtual void f() {cout<<"A::f()"<<endl;} void g() {cout<<"A::g()"<<endl;} void h() { cout<<"A::h()"<<endl; f(); g(); }};class B: public A{ public: void f() {cout<<"B::f()"<<endl;} void g() {cout<<"B::g()"<<endl;}};void main(){ B b; B * p=&b; p->h();}f(); g(); 00416E41 mov eax,dword ptr [this] 00416E44 mov edx,dword ptr [eax] 00416E46 mov esi,esp 00416E48 mov ecx,dword ptr [this] 00416E4B call dword ptr [edx] 00416E4D cmp esi,esp 00416E4F call @ILT+2795(__RTC_CheckEsp) (415AF0h) 00416E54 mov ecx,dword ptr [this] 00416E57 call A::g (4157FDh)
[解决办法]
我说说我的一点理解啊。
当这句 p->h(),派生类指针调用基类函数。此时要进行一个this指针的转换。
p->h()相当于h(this)
此时this是B*;但是h()是A的函数,因此要进行一个指针的转换为this(A*);
转换后h()内部调用调用虚函数f(),即this->f(),因此实现了多态。
其中的指针转换与A *pa=new B一样
[解决办法]