static_cast dynamic_cast:应为常量表达式

static_cast dynamic_cast: expected constant expression?

本文关键字:cast 常量 表达式 dynamic static      更新时间:2023-10-16

在visual C++2010中,当编译以下代码时,我收到错误消息:

static_cast错误C2057:应为常量表达式。

那怎么了?

struct A {};
struct B : A {};
struct XX
{
    static const int offset = (long)static_cast<A*>((B*)0x8) - 0x8;
};

感谢A程序员,以下是正确的VC 2010:

struct A {};
struct B : A {};
struct XX
{
    static const int offset;
};
const int XX::offset
 = (long)static_cast<A const*>((B const*)0x8) - 0x8;

对A*和B*的强制转换防止x的初始值设定项成为常量表达式:

5.19/3

算术常量表达式中的强制转换运算符只能将算术类型或枚举类型转换为算术类型或列举类型,作为sizeof运算符操作数的一部分除外。

在这种情况下需要:

9.2/4

成员声明符只能包含常量初始值设定项,前提是它声明了整型或枚举类型的static成员。

为什么不直接说:

static const int x =0x8;