将整数静态转换为指针类型 [英] Statically casting an integer to pointer type

查看:104
本文介绍了将整数静态转换为指针类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是不知道如何用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆