C++中如何在条件语句内为变量赋值const unsigned char类型位图?
问题解决:const unsigned char* 转 unsigned char* 编译错误
问题原因
你定义的位图数组是const unsigned char类型(只读数据),但drawBitmap函数的第三个参数是uint8_t*(与unsigned char*等价,非const指针)。C++禁止隐式将const指针转换为非const指针,这是类型安全机制,防止只读数据被意外修改,因此编译器抛出报错。
另外你原代码存在作用域问题:icon是在每个if分支内定义的局部变量,分支结束后变量就会销毁,后续无法调用drawBitmap使用它。
解决方案
方案1:修改函数参数(推荐,符合类型安全)
既然位图是只读的,函数无需修改其内容,直接将drawBitmap的参数改为const uint8_t*:
void drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color);
然后将icon定义在if语句外,类型改为const unsigned char*:
const unsigned char* icon; if (batteryChargePercent > 80) { icon = epd_bitmap_icon1; } else if (batteryChargePercent > 30) { icon = epd_bitmap_icon2; } else { icon = epd_bitmap_icon3; } // 若uint8_t与unsigned char是同一类型,可直接传入;否则用reinterpret_cast转换 drawBitmap(x, y, reinterpret_cast<const uint8_t*>(icon), w, h, color);
方案2:使用const_cast(仅当无法修改函数时)
如果drawBitmap是第三方库函数无法修改,可使用const_cast去除const属性,但必须确保函数不会修改传入的位图数据,否则会导致未定义行为(如程序崩溃、数据损坏):
unsigned char* icon; if (batteryChargePercent > 80) { icon = const_cast<unsigned char*>(epd_bitmap_icon1); } else if (batteryChargePercent > 30) { icon = const_cast<unsigned char*>(epd_bitmap_icon2); } else { icon = const_cast<unsigned char*>(epd_bitmap_icon3); } drawBitmap(x, y, icon, w, h, color);
方案3:移除位图数组的const属性(不推荐)
直接把头文件中的const unsigned char改为unsigned char,但会失去只读保护,误修改位图数据可能引发问题,因此不建议采用。
内容的提问来源于stack exchange,提问作者Adrian Ribao
相关产品推荐
相关产品推荐

