简体   繁体   English

具有多重继承的类的sizeof

[英]sizeof on class with multiple inheritance

First of all, I know sizeof depends on machine and compiler implementation. 首先,我知道sizeof取决于机器和编译器的实现。 I am using Windows 8.1. 我使用的是Windows 8.1。 x64, gcc 5.3.0., no flags are passed to the compiler. x64,gcc 5.3.0。,没有标志传递给编译器。
I have the following code from my university lecture: 我的大学讲座中有以下代码:

#include <iostream>
class A
{
    public:
        int a;
        int b;
        A(){ a = 1; b = 2; }
};

class S1 : public A {
    public:
        int x1;
        S1(){ x1 = 5;}
};

class S2 : public A {
    public:
        int x2;
        S2(){ x2 = 6;}
};

class S12 : public S1, public S2 {
    public:
       int x12;
       S12(){ x12 = 7;}
};

int main()
{
    std::cout << "S1: " << sizeof(A) << std::endl;
    std::cout << "S1: " << sizeof(S1) << std::endl;
    std::cout << "S2: " << sizeof(S2) << std::endl; 
    std::cout << "S12: " << sizeof(S12) << std::endl;
}

On my machine, I got the following output: 在我的机器上,我得到以下输出:
S1: 8 S1:8
S1: 12 S1:12
S2: 12 S2:12
S12: 28 S12:28

I can understand why S1 is 8 and S1,S2 are 12 bytes, but I don`t understand why S12 is 28 - I expect it to be 20, because it must have 5 integer variables (4 bytes each). 我可以理解为什么S1是8和S1,S2是12个字节,但我不明白为什么S12是28 - 我希望它是20,因为它必须有5个整数变量(每个4个字节)。
Why is S12 28 bytes? 为什么S12是28字节?

There are 7 integers in your class 你班上有7个整数

S1::A::a
S1::A::b
S1::x1
S2::A::a
S2::A::b
S2::x2
x12

S12 contains two A objects. S12包含两个 A对象。 If you want only one A object, you need to inherit virtually from it: 如果只需要一个A对象,则需要从中进行虚拟继承:

#include <iostream>    

struct A { int a = 1; int b = 2; };
struct S1 : virtual A { int x1 = 5; };
struct S2 : virtual A { int x2 = 6; };
struct S12 : S1, S2 { int x12 = 7; };
int main()
{
    std::cout << "A: " << sizeof(A) << std::endl;
    std::cout << "S1: " << sizeof(S1) << std::endl;
    std::cout << "S2: " << sizeof(S2) << std::endl; 
    std::cout << "S12: " << sizeof(S12) << std::endl;
}

The result you get will be much more implementation dependant than before - virtual base classes are tricky, and different compilers tend to use different implementation techniques for them. 您获得的结果将比以前更依赖于实现 - 虚拟基类很棘手,不同的编译器倾向于使用不同的实现技术。 I get: 我明白了:

A: 8
S1: 24
S2: 24
S12: 40

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM