static_cast dynamic_cast:期望的常量表达式?

问题描述

| 在Visual C ++ 2010中,当编译以下代码时,出现错误消息: static_cast错误C2057:预期的常量表达式。 这是怎么了?
struct A {};
struct B : A {};

struct XX
{
    static const int offset = (long)static_cast<A*>((B*)0x8) - 0x8;
};
感谢AProgrammer,以下内容适用于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   算术常数表达式中的强制转换运算符只能将算术或枚举类型转换为算术或枚举类型,但作为as2ѭ运算符的操作数的一部分除外。 在这种情况下需要: 9.2 / 4   成员声明符仅在声明整数或枚举类型的“ 3”成员时才可以包含常量初始化器。     ,        为什么不说:
static const int x =0x8;