【发布时间】:2022-01-20 02:18:15
【问题描述】:
error: conversion from ‘int’ to ‘char’ may change value [-Werror=conversion]
构建 cmd 示例:
g++ -std=c++11 test.cpp -o a.out -Werror=conversion
auto index = 3;
char singleChar = 'A' + index; // I want to get A-Z
我希望 sigleChar 是动态分配的。 你能帮我在不使用开关的情况下解决这个错误报告吗? 怎么写代码比较好?
【问题讨论】:
-
char singleChar = static_cast<char>('A' + index); -
您假设大写字母是一组连续的值(
'B' == 'A' + 1、'C' == 'B' + 1等)。 C++ 标准不保证这样的事情——而且现实世界的标准化字符集是不正确的。char singleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index]或(由于指针算法的交换性)index["ABCDEFGHIJKLMNOPQRSTUVWXYZ"]可能更简单。
标签: c++ algorithm char integer c++17