[英]Struct attribute inheritance in c++
Are the attributes of a struct inherited in C++ 结构的属性是否在C ++中继承
eg: 例如:
struct A {
int a;
int b;
}__attribute__((__packed__));
struct B : A {
list<int> l;
};
will the inherited part of struct B (struct A) inherit the packed attribute? struct B(struct A)的继承部分是否会继承packed属性?
I cannot add an a attribute (( packed )) to struct B without getting a compiler warning: 我不能在没有得到编译器警告的情况下向struct B添加一个属性 (( packed )):
ignoring packed attribute because of unpacked non-POD field
So I know that the entire struct B will not be packed, which is fine in my use case, but I require the fields of struct A to be packed in struct B. 所以我知道整个结构B不会打包,这在我的用例中很好,但我要求struct A的字段打包在struct B中。
Will the inherited part of struct B (struct A) inherit the packed attribute? struct B(struct A)的继承部分是否会继承packed属性?
Yes. 是。 The inherited part will still be packed. 继承的部分仍将被打包。 But the pack attribute itself is not inherited: 但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;
}
When called, I get 打电话的时候,我明白了
sizeof(B): 6
sizeof(C): 5
I think your warning comes from the list<> member which is a non-POD type and itself not packed. 我认为您的警告来自列表<>成员,该成员是非POD类型且本身未打包。 See also What are POD types in C++? 另请参阅C ++中的POD类型是什么?
Yes, the members of A
will be packed in struct B
. 是的, A
的成员将打包在struct B
。 It must be this way, otherwise it would break the whole point of inheritance. 它必须是这种方式,否则它将破坏整个继承点。 For example: 例如:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.