缩小从 int 到 unsigned char 的转换

Narrowing conversion from int to unsigned char

当我尝试编译这段代码时

struct T
{
    unsigned char x;
};

int main()
{
    unsigned char a = 10;
    unsigned char b = 1;

    T t = {a + b};

    return 0;
}

我收到此错误:

error: narrowing conversion of '(((int)a) + ((int)b))' from 'int' to 'unsigned char' inside { } [-Wnarrowing]|

谁能解释一下为什么?

您的加法表达式的操作数正在进行 integral promotion

In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value.

您的 ab 正在升级为 intunsigned int,已添加,然后又转换回 unsigned char

如果转换是预期的程序行为(从您作为设计者的角度来看),您可以将其显式转换为您想要的类型。显式转换不是缩小转换。隐式演员表是。因此,如果我们将隐式转换为显式转换,程序将不再是病式的。

T t = { static_cast<unsigned char>(a + b) };