正确的强制语法

JeC*_*eCh -1 c++ casting

我有这样的代码:

const quint8* data[2];    
const float *p0 = (float*)data[0]
Run Code Online (Sandbox Code Playgroud)

在QtCreator中,我收到警告:

"使用旧式演员".

我试着像这样写:

const float *p0 = const_cast<float*>(data[0])
Run Code Online (Sandbox Code Playgroud)

但我得到的另一个错误是类型之间无法生成.

什么应该是正确的语法?

bol*_*lov 7

好的,这就是答案:

const float *p0 = reinterpret_cast<const float*>(data[0]);
Run Code Online (Sandbox Code Playgroud)

要非常小心C++严格的别名规则.它们对你的例子的暗示是,p0 当且仅当 data[0]指向浮点对象时,你可以合法访问.例如

这是合法的

const float f = 24.11f;

const quint8* data[2] {};

data[0] = reinterpret_cast<const quint8*>(&f);
// for the above line:
// data[0] can legally alias an object of type float
//    if quint8 is typedef for a char type (which is highly likely it is)
// data[0] now points to a float object

const float *p0 = reinterpret_cast<const float*>(data[0]);
// p0 points to the float object f. Legal

float r = *p0; // legal because of the above

return r;
Run Code Online (Sandbox Code Playgroud)

这是非法的:

const quint8 memory[4]{};
memory[0] = /* ... */;
memory[1] = /* ... */;
memory[2] = /* ... */;
memory[3] = /* ... */;

const quint8* data[2] {};

data[0] = memory;
// data[0] doesn't point to a float object

const float *p0 = reinterpret_cast<const float*>(data[0]);
// no matter what trickery you use to get the cast
// it is illegal for a `float*` pointer to alias a `quint8[]` object

float r = *p0; // *p0 is illegal and causes your program to have Undefined Behavior
Run Code Online (Sandbox Code Playgroud)