将整数静态转换为指针类型 [英] Statically casting an integer to pointer type
问题描述
我只是不知道如何用C ++编译这个简单的例子:
I just can't find out how this simple example can be compiled in C++ :
class C
{
public:
static const void* noop = static_cast<const void*> (0x1);
};
由于我想要的static
存储限制,此处唯一可能的转换是static_cast
,但它与此int-to-ptr转换不兼容.
Because of the static
storage constraint I want, the only cast possible here would be static_cast
but it is incompatible with this int-to-ptr cast.
错误:从"int"类型到"const void *"类型的static_cast无效
error: invalid static_cast from type ‘int’ to type ‘const void*’
如何将整数值静态转换为指针类型?
How can an integer value be statically casted to a pointer type?
推荐答案
此处的问题是,尽管您声明了const void*
,但const
限定词并不适用于指针,而是适用于该指针指向的地址
The problem here is that although you are declaring a const void*
the const
qualifier doesn't apply to the pointer but to the address that this pointer points to.
这意味着noop
不是static const
成员变量,并且所有非const static
成员变量都需要在class
定义之外的单个转换单元中定义和初始化,如下例所示:
This means that noop
is not a static const
member variable and as all non const static
member variables needs to be defined and initialized in a single translation unit outside class
's definition like the example below:
class C {
public:
static const void *noop;
};
const void* C::noop = (const void*) 0x1;
Live Demo
以下解决方案:
class C {
public:
static constexpr const void* noop = reinterpret_cast<const void*>(0x1);
};
尽管如此,但它在GCC中并不是有效的C ++(例如,它不能与clang或VC ++ 2013一起编译),并且可以在GCC中正常工作,因为根据标准§5.19/2常量表达式[expr .const] reinterpret_cast
的结果不能是常量表达式.
Although, it compiles and works fine in GCC isn't valid C++ (e.g., it doesn't compile with either clang or VC++2013) because according to the standard § 5.19/2 Constant Expressions [expr.const] the result of a reinterpret_cast
can't be a constant expression.
这篇关于将整数静态转换为指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!