c++ - 不一致的警告 "conversion from ' const unsigned char' to 'const float' requires a narrowing conversion”

标签 c++ c++11 gcc visual-c++ gcc-warning

Visual C++ 2017 和 gcc 5.4 产生 conversion from 'const unsigned char' to 'const float' requires a narrowing conversion 警告 Line 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';
}

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

最佳答案

警告有效,来自 C++11 narrowing conversionsaggregate initialization 中被禁止;但未应用于 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

顺便说一句:c[0]c[1]c[2]not constant expressions ;您可以将数组声明为 constexpr,即 constexpr unsigned char c[3] = {0, 1, 255};。然后应用异常并 Line B也可以正常工作。

关于c++ - 不一致的警告 "conversion from ' const unsigned char' to 'const float' requires a narrowing conversion”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012820/

相关文章:

c++ - Ofstream 在 Ubuntu 上创建隐藏(?)文件(同时打开)

c++ - 模板特化 - clang 和 gcc 的不同结果

c++ - cygwin 在 g++4.9.2 中支持 C++11

c++11 - 禁用 gcc 中的覆盖检查

c - 如何计算gcc编译时间?

c - SDL2 事件在 C 中不起作用

c++ - 从 C 包含并编译 C++ 头文件

c++ - 与模板化成员方法同名的普通成员方法

c++ - 读取私有(private)变量类成员

c++ - 在模板类中使用 std::allocator 时出错