首页 > 解决方案 > 从 const 字符串转换为 const u8_t 时出现问题 *

问题描述

我有以下代码

在 .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 u8_t *最终将 const 字符串转换为。u8_t 是无符号字符

标签: c++castingtype-conversion

解决方案


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());

推荐阅读