static_cast dynamic_cast:应为常量表达式
static_cast dynamic_cast: expected constant expression?
在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;
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 如何理解C++标准N3337中的expr.const.cast子句8
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- C++Cast运算符过载
- 私有类型的静态常量成员
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我可以通过引用修改常量返回
- 如何创建长度由常量参数指定的数组
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 通过使用 const-cast 的非常量引用来延长临时的寿命