【问题标题】:reinterpret_cast invalid but static_cast is fine [duplicate]reinterpret_cast 无效但 static_cast 很好[重复]
【发布时间】:2021-11-10 15:12:44
【问题描述】:

我是 C++ 中显式转换的新手。我认为 static_cast 比 reinterpret_cast 更具限制性。但是,我有一个函数,其中 static_cast 给了我想要的结果,而 reinterpret_cast 告诉我我的转换无效。为什么会这样?

void    from_int(int x)
{
    if (x < 32 || x > 126)
        std::cout << "char: Non displayable" << std::endl;
    std::cout << "char: '" << reinterpret_cast<char>(x) << "'" << std::endl;
    std::cout << "int: " << x << std::endl;
    std::cout << "float: " << x << ".0f" << std::endl;
    std::cout << "double: " << x << ".0" << std::endl;
}

【问题讨论】:

标签: c++ casting reinterpret-cast static-cast


【解决方案1】:

static_castreinterpret_cast 在执行从一种指针类型到另一种类型的转换时更具限制性。使用reinterpret_cast,这样的转换将始终编译(假设转换是从对象指针到对象指针或函数指针到函数指针)。

reinterpret_cast 专门针对此类指针强制转换、类似引用强制转换以及指针和整数类型之间的强制转换。您在这里要做的是执行隐式转换。在这种情况下,以及当您想要执行隐式转换的reverse 时,static_cast 通常是正确的选择。一些程序员使用用户定义的“implicit_cast”模板,它甚至比static_cast 更弱,但更安全(它只执行隐式转换)。

【讨论】:

    猜你喜欢
    • 2013-10-14
    • 2012-02-26
    • 2016-05-28
    • 2013-12-21
    • 2013-10-18
    • 2011-10-14
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多