gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:55:32 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com