多重继承:虚拟指针的类的大小? [英] Multiple Inheritance : size of class for virtual pointers?

查看:127
本文介绍了多重继承:虚拟指针的类的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

  class A {}; 

class B:public virtual A {};

class C:public virtual A {};

class D:public B,public C {};

int main(){
cout<<sizeof(D)<
return 0;
}

输出:
sizeof(D)8



每个类都包含自己的虚指针,而不是它的基类的任何一个
那么,为什么类(D)的Size是8?

解决方案

这取决于编译器的实现。我的编译器是Visual Stdio C ++ 2005。



这样的代码:

  int main(){
cout<<sizeof(B):<< sizeof(B)< endl;
cout<<sizeof(C):<< sizeof(C)< endl;
cout<<sizeof(D):<< sizeof(D)<< endl;
return 0;
}

它会输出

  sizeof(B):4 
sizeof(C):4
sizeof(D):8
pre>

类B只有一个虚指针。因此 sizeof(B)= 4 。而且C类也是。



但是D多继承类B class C 。编译不合并两个虚表。类D 有两个虚指针指向每个虚表。



如果D只继承一个类而不是虚拟继承。它会合并他们的虚表。


Given the code:

class A{};

class B : public virtual A{};

class C : public virtual A{};

class D : public B,public C{};

int main(){
cout<<"sizeof(D)"<<sizeof(D);
return 0;
}

Output: sizeof(D) 8

Every class contains its own virtual pointer only not of any of its base class, So, why the Size of class(D) is 8?

解决方案

It depends on compiler implementation. My compiler is Visual Stdio C++ 2005.

Code like this:

int main(){
    cout<<"sizeof(B):"<<sizeof(B) << endl;
    cout<<"sizeof(C):"<<sizeof(C) << endl;
    cout<<"sizeof(D):"<<sizeof(D) << endl;
    return 0;
} 

It will output

sizeof(B):4
sizeof(C):4
sizeof(D):8

class B has only one virtual pointer. So sizeof(B)=4. And class C is also.

But D multiple inheritance the class B and class C. The compile don't merge the two virtual table.So class D has two virtual pointer point to each virtual table.

If D only inheritance one class and not virtual inheritance. It will merge they virtual table.

这篇关于多重继承:虚拟指针的类的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆