c ++中的struct属性继承

squ*_*ter 5 c++

结构的属性是否在C++中继承

例如:

struct A {
    int a;
    int b;
}__attribute__((__packed__));

struct B : A {
    list<int> l;
};
Run Code Online (Sandbox Code Playgroud)

struct B(struct A)的继承部分是否会继承packed属性?

我不能在没有得到编译器警告的情况下向struct B 添加一个属性((packed)):

ignoring packed attribute because of unpacked non-POD field
Run Code Online (Sandbox Code Playgroud)

所以我知道整个结构B不会打包,这在我的用例中很好,但我要求struct A的字段打包在struct B中.

And*_*ter 5

struct B(struct A)的继承部分会继承packed属性吗?

是的。继承的部分仍然会被打包。但 pack 属性本身是不被继承的:

#include <stdio.h>

#include <list>
using std::list;

struct A {
    char a;
    unsigned short b;
}__attribute__((__packed__));

struct B : A {
    unsigned short d;
};

struct C : A {
    unsigned short d;
}__attribute__((__packed__));

int main() {
   printf("sizeof(B): %lu\n", sizeof(B));
   printf("sizeof(C): %lu\n", sizeof(C));

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

当被叫时,我得到

sizeof(B): 6
sizeof(C): 5
Run Code Online (Sandbox Code Playgroud)

我认为您的警告来自 list<> 成员,它是非 POD 类型,并且本身未打包。另请参阅C++ 中的 POD 类型是什么?


ten*_*our 4

是的, 的成员A将被打包在struct B. 必须如此,否则就破坏了传承的全部意义。例如:

std::vector<A*> va;
A a;
B b;
va.push_back(&a);
vb.push_back(&b);

// loop through va and operate on the elements. All elements must have the same type and behave like pointers to A.
Run Code Online (Sandbox Code Playgroud)