【问题标题】:What's the difference between (const_cast<char*> and without?(const_cast<char*> 和没有之间有什么区别?
【发布时间】:2021-10-27 07:04:39
【问题描述】:

我很难理解这两个命令之间的区别

        char name[0x36];
        sprintf_s(name, "Some Text (%d%% Water) [%dm]", amount, dist);
        Drawing::RenderText(const_cast<char*>(name), screen, cfg.visuals.ships.textCol);

和

        char name[0x36];
        sprintf_s(name, "Some Text (%d%% Water) [%dm]", amount, dist);
        Drawing::RenderText(name, screen, cfg.visuals.ships.textCol);

这是 RenderText 函数:

void xD::Renderer::Drawing::RenderText(const char* text, const FVector2D& pos, const ImVec4& color, const bool outlined = true, const bool centered = true)
{
    if (!text) return;
    auto ImScreen = *reinterpret_cast<const ImVec2*>(&pos);
    if (centered)
    {
        auto size = ImGui::CalcTextSize(text);
        ImScreen.x -= size.x * 0.5f;
        ImScreen.y -= size.y;
    }
    auto window = ImGui::GetCurrentWindow();

    if (outlined) 
    { 
        window->DrawList->AddText(nullptr, 0.f, ImVec2(ImScreen.x - 1.f, ImScreen.y + 1.f), ImGui::GetColorU32(IM_COL32_BLACK), text); 
    }

    window->DrawList->AddText(nullptr, 0.f, ImScreen, ImGui::GetColorU32(color), text);

}

我正在使用 ImGui

【问题讨论】:

  • 对我来说,const_cast 的使用似乎并不正确。你在哪里看到的?
  • 实际上没有区别,也不需要演员表。编译器会将(衰减的)指向字符串的指针隐式转换为const。
  • 另一方面,对于数组大小使用十六进制文字是非常不寻常的,除非它们依赖于一些在十六进制中更容易理解的二进制值。为什么要使用 C 风格的字符串(char 数组和非标准的 sprintf_s(无论如何你都用错了))而不是 C++ std::string?请记住,std::string 有一个 c_str() 函数来获取 C 风格的“字符串”(指向以 null 结尾的数组的第一个字符的指针)。
  • reinterpret_cast-ing 到 ImVec2 在技术上是未定义的。最好在ImVec2 中定义一个构造函数和一个转换运算符来与你的向量进行转换,ImGui 有一个配置宏可以让你做到这一点。
  • @HolyBlackCat 你能给我看看吗?也许不和谐? Kierak#8418

标签: c++ imgui


【解决方案1】:

(const_cast 和没有有什么区别?

不同之处在于,在一种情况下,转换是隐式的,而在另一种情况下,转换是显式的。没有其他区别。

【讨论】:

  • 这意味着我不应该使用 (const_cast 因为它可能会导致不必要的问题/编译器问题?
  • @noone 在这种情况下 - 这只是浪费打字,因为两者产生相同的结果。
  • @noone 当您不明白为什么要使用它们或是否应该使用它们时,您不应该使用强制转换。在这种情况下,您不需要使用它,但可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 2020-06-26
  • 2015-03-12
  • 2010-12-14
  • 2012-08-14
相关资源
最近更新 更多