作者descent (「雄辩是银,沉默是金」)
看板C_and_CPP
标题[问题] narrowing conversion
时间Wed Apr 5 15:10:36 2017
开发平台(Platform): (Ex: Win10, Linux, ...)
linux 64bit
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
g++
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
no
问题(Question):
#include <typeinfo>
#include <iostream>
using namespace std;
class A
{
public:
A(long a)
{
cout << a << endl;
}
};
int main(int argc, char *argv[])
{
/* aa */ A a{0xffff0000};
// 会有 error: narrowing conversion of '4294901760u' from
'unsigned int' to 'long int' inside { } [-Wnarrowing]
/* bb */ A a(0xffff0000); // 可以正确编译
}
0xffff0000 的 type 是 unsigned int, 我使用 -m32 编译出 x86 32bit 程式码。
从 unsigned int to long (x86 32bit 环境), 应该会有 narrowing conversion
的错误, 可是使用 bb 的语法, 就不会有这样的错误讯息。
我猜测 bb 的语法做了 implicit conversion, 但 aa 那个语法是怎麽处理的呢?
编译指令:
g++ -m32 -std=c++14 b.cpp -o b
当然如果是在 x86 64 环境, 没有任何问题, long 是 64bit, 可以装得下
unsigned int。
补充:
查到了, {} 语法不允许 narrowing conversion。
c++ 标准库 p15
--
纸上得来终觉浅,绝知此事要躬行。
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 113.196.174.254
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1491376251.A.F2C.html
※ 编辑: descent (113.196.174.254), 04/05/2017 16:30:35
1F:推 loveflames: 又多了一个使用list initialization的好处,算是吧 04/05 16:58