gpt4 book ai didi

c++ - C++中的结构属性继承

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:15 25 4
gpt4 key购买 nike

C++中结构体的属性是继承的吗

例如:

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

struct B : A {
list<int> l;
};

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

我无法在没有收到编译器警告的情况下将 a 属性((packed)) 添加到结构 B:

ignoring packed attribute because of unpacked non-POD field

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

最佳答案

Will the inherited part of struct B (struct A) inherit the packed attribute?

是的。继承的部分仍然会被打包。但是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;
}

当被调用时,我得到

sizeof(B): 6
sizeof(C): 5

我认为您的警告来自 list<> 成员,该成员是非 POD 类型且本身未打包。另见 What are POD types in C++?

关于c++ - C++中的结构属性继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com