gpt4 book ai didi

c++ - static_cast 动态_cast : expected constant expression?

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:06 25 4
gpt4 key购买 nike

在 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

Cast operators in an arithmetic constant expression shall only convert arithmetic or enumeration types to arithmetic or enumeration types, excepted as part of an operand to the sizeof operator.

在这种情况下需要:

9.2/4

A member-declarator can contain a constant-initializer only if it declares a static member of integral or enumeration type.

关于c++ - static_cast 动态_cast : expected constant expression?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6189155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com