是否可以禁止在C ++中基本类型之间进行隐式转换?特别是,我想从禁止隐式转换unsigned
到float
或double
因为像这些错误的:
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.
我尝试过这样的事情:
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
如果编写的函数带有double
,则可以通过为整数类型添加重载然后删除它们来防止传递整数类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句