Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
禁止隐式“unsigned”到“double”转换 是否允许禁止C++中的基本类型之间的隐式转换?特别是,我想禁止从无符号到浮点或双精度的隐式转换,因为有如下错误: int i = -5; ... unsigned u = i; // The dawn of the trouble. ... double d = u; // The epicenter of the bug that took a day to fix._C++_Floating Point_Unsigned - Fatal编程技术网

禁止隐式“unsigned”到“double”转换 是否允许禁止C++中的基本类型之间的隐式转换?特别是,我想禁止从无符号到浮点或双精度的隐式转换,因为有如下错误: int i = -5; ... unsigned u = i; // The dawn of the trouble. ... double d = u; // The epicenter of the bug that took a day to fix.

禁止隐式“unsigned”到“double”转换 是否允许禁止C++中的基本类型之间的隐式转换?特别是,我想禁止从无符号到浮点或双精度的隐式转换,因为有如下错误: int i = -5; ... unsigned u = i; // The dawn of the trouble. ... double d = u; // The epicenter of the bug that took a day to fix.,c++,floating-point,unsigned,C++,Floating Point,Unsigned,我试过这样的方法: explicit operator double( unsigned ); 不幸的是,这不起作用: explicit.cpp:1: error: only declarations of constructors can be ‘explicit’ explicit.cpp:1: error: ‘operator double(unsigned int)’ must be a nonstatic member function 不能简单地从语言中完全删除隐式标准转换 话虽

我试过这样的方法:

explicit operator double( unsigned );
不幸的是,这不起作用:

explicit.cpp:1: error: only declarations of constructors can be ‘explicit’
explicit.cpp:1: error: ‘operator double(unsigned int)’ must be a nonstatic member function

不能简单地从语言中完全删除隐式标准转换

话虽如此,在某些情况下,有一些方法可以防止不希望的转换。在初始化期间,可以使用大括号语法防止缩小转换范围。浮动类型和整数类型之间的转换始终被视为缩小范围(编辑:源为整型常量表达式时除外)

如果编写的函数采用
双精度
,则可以通过为整数类型添加重载,然后删除它们来防止传递整数类型

int i {-5};       // ok; -5 fits in an int
unsigned u = i;   // ok; no check for narrowing using old syntax
double d {u};     // error: narrowing