通过虚函数表可以访问到对象的布局,通过函数指针可以运行函数,不论是private还是public,于是单继承、非virtual的demo如下:
-
#include <iostream>
-
-
class A
-
{
-
public:
-
A ( ): x ( 5 ) { }
-
-
private:
-
virtual void fun ( ) { std:: cout << "A::fun()" << std:: endl; }
-
-
private:
-
int x;
-
};
-
-
class B: public A
-
{
-
public:
-
B ( ): y ( 3 ) { }
-
-
private:
-
virtual void fun ( ) { std:: cout << "B::fun()" << std:: endl; }
-
-
private:
-
int y;
-
};
-
-
typedef void (*Fun ) ( );
-
-
void PrintVTable (Fun* pVT )
-
{
-
Fun* pFun = pVT;
-
while ( *pFun )
-
{
-
(*pFun ) ( );
-
pFun ++;
-
}
-
}
-
-
void PrintMembers ( int* pMembers )
-
{
-
std:: cout << *pMembers << std:: endl;
-
}
-
-
void PrintVTableAndMembers (B* ptr )
-
{
-
int* pAddress = ( int* ) ptr;
-
PrintVTable ( (Fun* ) *pAddress );
-
pAddress ++;
-
-
PrintMembers (pAddress );
-
pAddress ++;
-
-
PrintMembers (pAddress );
-
pAddress ++;
-
}
-
-
void main ( void )
-
{
-
B b;
-
-
PrintVTableAndMembers (&b );
-
-
system ( "pause" );
-
}
如果是多继承 或者 继承方式用virtual,对象的布局是不一样的,可以参考下本文:http://yoyo.is-programmer.com/posts/10671.html