注:标题中所说的实函数是指普通成员函数
A为基类,继承关系如图
A
|
B
|
C
|
D
伪代码如下:
B *pb = new C;
pb->f1();
总结:
1.调用从基类继承来的成员函数,在子类中未有重写覆盖(overriding),函数内部的this指针为基类类型
2.调用虚函数,当有重写覆盖时,虚函数内部保存的指针为子类类型,当未有重写覆盖上时规则同上
3.调用普通成员函数时,this指针可能上升(从子类转为基类)
4.调用虚函数时,this指针可能上升也可能下降(从基类转为子类),但是不会下降到子类实体对象以下
测试代码如下:
#include <iostream.h>
//--------------------------------------------------------------------------------
class A
{
public:
void f1(){
cout<<"A::f1()"<<endl;
f2();
}
virtual void f2(){
cout<<"A::f2()"<<endl;
f3();
}
void f3(){
cout<<"A::f3()"<<endl;
f4();
}
void f4(){
cout<<"A::f4()"<<endl;
}
};
//--------------------------------------------------------------------------------
class B: public A
{
public:
/*
void f1(){
cout<<"B::f1()"<<endl;
f2();
}
*/
virtual void f2(){
cout<<"B::f2()"<<endl;
f3();
}
void f3(){
cout<<"B::f3()"<<endl;
f4();
}
};
//--------------------------------------------------------------------------------
class C: public B
{
public:
void f1(){
cout<<"C::f1()"<<endl;
f2();
}
virtual void f2(){
cout<<"C::f2()"<<endl;
f3();
}
/*
void f3(){
cout<<"C::f3()"<<endl;
f4();
}
*/
void f4(){
cout<<"C::f4()"<<endl;
}
};
//--------------------------------------------------------------------------------
class D: public C
{
public:
void f1(){
cout<<"D::f1()"<<endl;
f2();
}
virtual void f2(){
cout<<"D::f2()"<<endl;
f3();
}
void f3(){
cout<<"D::f3()"<<endl;
}
};
//--------------------------------------------------------------------------------
int main(void)
{
B *pb = new C;
pb->f1();
return 0;
}