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

标签 c++

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/

相关文章:

c++ - friend 和模板 C++

c++ - 可以组合部分模板特化来生成隐式生成的共享代码路径吗?

c++ - 在带有 mingw64 的 Visual Studio Code 中找不到 #include <iostream>

c++ - 如何使用 OLEDB API 获取给定 SQL Server Compact Edition 数据库文件 (.sdf) 的版本?

c++ - 如何在cpp中以有效的方式比较 vector 和数组?

c++ - 无法在 boost-python 中导入 numpy

c++ - VSCode 、 cmake debug 未在 Windows PC 上提供输出

c++ - 如何在应用程序上使用英特尔引脚工具?

C++ 设置搜索对元素?

c++ - 如何通过引用将数组传递给函数模板