我有一个非虚拟最终类,它只声明相同类型的字段。
struct Vector3 final
{
float X, Y, Z;
Vector3(float x, float y, float z) : X(x), Y(y), Z(z)
{
}
float Sum()
{
return X + Y + Z;
}
};
将指向此类实例的指针重新解释为 float 组是否安全?
int main(int argc, const char *argv[])
{
Vector3 v(10, 20, 30);
Vector3 *pV = &v;
float *ff = reinterpret_cast<float*>(pV);
std::cout << ff[0] << std::endl << ff[1] << std::endl << ff[2] << std::endl;
char c;
std::cin >> c;
return 0;
}
最佳答案
不,它不是——数据成员之间可能有填充。
关于c++ - c++ final 非虚拟类是否被重新解释为可以安全使用的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21052836/