考虑以下代码:
#include <cstdint>
class A
{
public:
explicit A(uint8_t p_a){ m_a = p_a; };
uint8_t get_a() const {return m_a;}
private:
uint8_t m_a;
};
int main()
{
A a {0x21U};
A aa{0x55U};
uint8_t mask{a.get_a() | aa.get_a()};
return 0;
}
当我尝试编译这个 ( gcc 5.4.0
) 时,我收到以下错误:
main.cpp: In function ‘int main()’:
main.cpp:20:28: warning: narrowing conversion of ‘(int)(a.A::get_a() | aa.A::get_a())’ from ‘int’ to ‘uint8_t {aka unsigned char}’ inside { } [-Wnarrowing]
uint8_t mask{a.get_a() | aa.get_a()};
我真的不明白为什么会有任何缩小。该int
类型从未在我的代码中的任何地方使用过,所有内容都是用unsigned char
s 编写的。即使我明确地转换为unsigned char
我得到错误:
uint8_t mask{static_cast<uint8_t>(a.get_a()) | static_cast<uint8_t>(aa.get_a())};
其实要解决这个问题,我需要去掉{}
-initialization。然后它工作:
uint8_t mask = a.get_a() | aa.get_a();
为什么这是必要的?