我有一个包含一组结构的全局包含文件。在我程序的某处,我有一个包含成员数组的类。该数组中的元素数量取决于特定结构中特定字段的大小。我想这样做,以便在结构字段的大小发生更改时自动更新数组大小。我已经能够使用以下表达式成功地做到这一点:
bool shadowChkBox[sizeof(FSCconfigType::WriteEn)*8*MAX_FSCS];
FSCconfigType 是结构类型,WriteEn 是字段之一。现在这有效但只在 ubuntu 上。在 RHEL 5 上,编译器将其声明为错误。我还有什么其他选择可以做到这一点?我正在使用 Qt。
最佳答案
这是一个可能的答案:
#include <iostream>
struct A
{
int a;
int b;
int c;
};
bool items[sizeof(reinterpret_cast<A *>(0)->b)];
int main()
{
std::cout << sizeof(reinterpret_cast<A *>(0)->b) << ",";
std::cout << sizeof(items) << std::endl;
return 0;
}
关于c++ - 数组大小取决于 sizeof() 结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4299276/