您的位置:首页 > 编程语言 > C语言/C++

c++虚函数以及虚继承图示

2012-07-16 08:39 621 查看
1. 一般单一继承





只有一个虚表指针,虚表包含所有的虚函数

思考:1. 如果将GrandChild中的h_grandchild前面的virtual去掉,内存中的唯一变化是虚表缺少一项GrandChild::h_grandchild

2. 如果是child: virtual public parent?

output:

addr:0014FA44 sizeof = 28

0:

f1783c = f110c8

GrandChild::g_child()//这个时候要注意,虚函数表里没有f//可以这样理解,虚函数表内的函数和非虚拟继承是一样的,但是基类的位置不一样

Child::h_child()

GrandChild::h_grandchild()

1:

f1784c = fffffffc

fffffffc

10

2:

100

3:

1000

4:

0

5:

f17828 = f11041

GrandChild::f()

Parent::g()

Parent::h()

6:

10

虚基类肯定是放在最后,但是虚函数表中的内容就比较纠结,只放自己被重载的函数。

child和grandchild的指针地址相同,parent的指针地址在最后

2. 一般多继承





3. 虚基类的多继承



请参考:/article/7918004.html

附上本人检测内存分布的函数:

typedef void (*Fun)(void);
GrandChild b;
int *ptr;
/*B b;*/
ptr = (int*)&b;
cout <<"addr:" << ptr << " sizeof = " << sizeof(GrandChild) <<endl;
Fun pFun = NULL;
/* Fun pFun = (Fun ) ((int*)ptr[0])[0];
pFun();*/
cout<<"parent:"<<(Parent *)&b<<endl<<"child:"<<(Child *)&b<<endl<<"grandchild:"<<&b<<endl;
for(int i=0;i<sizeof(GrandChild)/sizeof(int);i++)
{
cout<<i<<":"<<endl;
if(ptr[i] < 10000)
{
cout << dec << ptr[i]<<endl;
}
else
{
cout << hex << ptr[i] <<" = " << hex << * ((int*)(ptr[i])) <<endl;
int *p = (int*)(ptr[i]);
if(*p==-4)
{
cout<<" "<<p[0]<<endl;
cout<<" "<<p[1]<<endl;
}
else
{
while(*p!=0)
{
pFun = (Fun )(*p);
//cout<<" "<<;
//cout.flush();
pFun();

++p;
}
}
}
}


本文中的图片均来自:http://blog.csdn.net/haoel
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: