比较 double 和 int

san*_*ark 6 c++ comparison type-safety

在阅读《C++ 编程原理与实践》一书时,第 3 章指出我们不能直接将 double 与 int 进行比较。但是,当我在 Visual Studio 上测试它时,它运行良好,没有错误?他说无法将 double 与 int 进行比较是什么意思?后来,他解释说C++提供了一种间接的方式。他的意思是隐式转换吗?

Hol*_*olt 6

C++ 在[over.built]中定义了一组内置运算符。相等运算符的行为在[expr.eq]中定义,特别是:

6如果两个操作数都是算术或枚举类型,则对两个操作数都进行通常的算术转换;如果指定的关系为 true,则每个运算符应生成 true;如果指定的关系为 false,则每个运算符应生成 false。

通常的算术转换意味着:

(1.3)否则,如果任一操作数为 double,则另一个操作数应转换为 double。

因此,如果将 anint与 a float、 adouble或 a进行比较long double,则会得到从intto floatdoubleor 的隐式转换long double


wal*_*lly 5

是的,存在隐式转换。

考虑以下程序:

bool f()
{
    return 3 == 3.0;
}
Run Code Online (Sandbox Code Playgroud)

如果您查看Clang 生成的 AST,您就会看到隐式转换是在哪里完成的。Clang 称其为ImplicitCastExpr

  `-BinaryOperator <col:12, col:17> 'bool' '=='
    |-ImplicitCastExpr <col:12> 'double' <IntegralToFloating>
    | `-IntegerLiteral <col:12> 'int' 3
    `-FloatingLiteral <col:17> 'double' 3.000000e+00
Run Code Online (Sandbox Code Playgroud)