最近,我注意到C/C++似乎是非常允许的数字类型转换,因为它隐式地将一个double转换为int.
测试:
环境:cpp.sh
,Standard C++ 14
,Compilation warnings all set
码:
int intForcingFunc(double d) {
return d; // this is allowed
}
int main() {
double d = 3.1415;
double result = intForcingFunc(d);
printf("intForcingFunc result = %f\n", result);
int localRes = d; // this is allowed
printf("Local result = %d\n", localRes);
int staticCastRes = static_cast<int>(d); // also allowed
printf("Static cast result = %d\n", staticCastRes);
}
Run Code Online (Sandbox Code Playgroud)
编译期间没有警告问题.
文档提到切向主题,但错过了问题的确切情况:
C++是一种强类型语言.许多转换,特别是那些暗示对值的不同解释的转换,需要显式转换,在C++中称为类型转换.
我也尝试过托管语言(C#),并且不允许所有这些情况(如预期的那样):
static int intForcingFunc(double d)
{
// Not …
Run Code Online (Sandbox Code Playgroud)