c – 不一致的警告“从’const unsigned char’转换为’const float’需要缩小转换”

Visual C 2017和 gcc 5.4生成从’const unsigned char’到’const float’的转换需要对B行进行缩小转换警告,但在此代码段中不需要对A行进行转换:
#include <iostream>

int main() {
    const unsigned char p = 13;
    const float         q = p;  // Line A

    std::cout << q << '\n';

    const unsigned char c[3] = {0,1,255};
    const float         f[3] = {c[2],c[0],c[1]};  // Line B

    for (auto x:f)
        std::cout << x << '\n';
}

这个警告有效吗?为什么B线的处理方式与A线不同?

解决方法

警告有效,@L_403_1@禁止C 11 narrowing conversions;但未在 copy initialization中应用(如前所述).

If the initializer clause is an expression,implicit conversions are allowed as per copy-initialization,except if they are narrowing (as in list-initialization) (since C++11).

Until C++11,narrowing conversions were permitted in aggregate initialization,but they are no longer allowed.

list-initialization limits the allowed implicit conversions by
prohibiting the following:

  • conversion from an integer type to a floating-point type,except where the source is a constant expression whose value can be stored
    exactly in the target type

BTW:c [0],c [1]和c [2]是not constant expressions;你可以将数组声明为constexpr,即constexpr unsigned char c [3] = {0,255};.然后应用异常,Line B也可以正常工作.

相关文章

/** C+⬑ * 默认成员函数 原来C++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录&lt;future&gt;future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...