【问题标题】:Issue while converting from const string to const u8_t *从 const 字符串转换为 const u8_t 时出现问题 *
【发布时间】:2020-10-27 07:53:57
【问题描述】:

我有以下代码

在 .hpp 文件中

class A
{
 private:
   static std::string hello;
}

在 .cpp 文件中

const std::string hello= "hi";

B(hello, strlen(hello)); // where B(const u8_t* a, u8_t b)

我应该使用哪种演员表? 我想最终将 const 字符串转换为 const u8_t * 。 u8_t 是无符号字符

【问题讨论】:

  • hello.c_str() ?
  • 不要使用u8_t。在<cstdint>中使用uint8_t
  • 什么是u8_t?请出示minimal reproducible example
  • u8_t = 无符号字符

标签: c++ casting type-conversion


【解决方案1】:

u8_t 是非标准类型。我假设它与标准 uint8_t 相同。

另一个悬而未决的问题是B 类型是否以任何特殊方式处理空字节,我假设不会。

所以strlen(hello) 无法编译。那应该换成hello.size(),这是获取C++字符串大小的正确方法。

最后回答你的问题,std::string 有一个data 方法,它返回一个指向字符数据的指针。该指针是 char* 类型,然后您需要将其转换为 u8_t* 用于您的构造函数。

所以把它们放在一起就得到了

B(reinterpret_cast<u8_t*>(hello.data()), hello.size());

【讨论】:

  • 这是推广的好习惯吗?他/她/他们不应该使用std::bit_cast(或memcpy pre c++20)吗?
  • John,我收到了这个错误 - “reinterpret_cast 不能抛弃 const 或其他类型限定符 C/C++(694)”。通过使用 hello.size() ,我不再有问题。但在选角方面仍有问题。
  • @RajLavingia OK 如果helloconst,只需将代码更改为此B(reinterpret_cast&lt;const u8_t*&gt;(hello.data()), hello.size());
猜你喜欢
  • 2013-02-15
  • 1970-01-01
  • 2023-02-15
  • 2013-07-25
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
相关资源
最近更新 更多