c++ - 为什么 Clang 将显式强制转换解释为隐式强制转换?

标签 c++ c casting clang

我最近一直在使用 Clang,这种小小的好奇心总是在解析显式转换时出现。

为了明确我的观点,这里有一些基本代码:

int main(){
    int my_int; 
    float my_float; 

    my_int = (int) my_float; 
    return 0; 
} 

当然,您会期望 my_int = (int) my_float; 被解析为 CStyleCastExpr ,带有 CastKind CK_FloatingToIntegral 的,但事实并非如此,事实上,强制转换的性质存储在 ImplicitCastExpr 中。而CStyleCastExpr则具有NoOp性质。

这是此代码的匹配 AST 转储:

|-DeclStmt 0x2eb3528 <line:3:1, col:11>
| `-VarDecl 0x2eb34d0 <col:1, col:5> my_int 'int'
|-DeclStmt 0x2eb35a8 <line:4:1, col:15>
| `-VarDecl 0x2eb3550 <col:1, col:7> my_float 'float'
|-BinaryOperator 0x2eb3678 <line:5:1, col:16> 'int' lvalue '='
| |-DeclRefExpr 0x2eb35c0 <col:1> 'int' lvalue Var 0x2eb34d0 'my_int' 'int'
| `-CStyleCastExpr 0x2eb3650 <col:10, col:16> 'int' <NoOp>
|   `-ImplicitCastExpr 0x2eb3638 <col:16> 'int' <FloatingToIntegral>
|     `-ImplicitCastExpr 0x2eb3620 <col:16> 'float' <LValueToRValue>
|       `-DeclRefExpr 0x2eb35e8 <col:16> 'float' lvalue Var 0x2eb3550 'my_float' 'float'
`-ReturnStmt 0x2eb36c0 <line:6:1, col:8>
  `-IntegerLiteral 0x2eb36a0 <col:8> 'int' 0

这似乎有点令人困惑,因为对我来说,ImplicitCastExpr 应该仅在发生某些意外转换时才被识别(请参阅下面的代码)。

int main(){
    int my_int;
    float my_float; 

    // implicit cast from float to int
    my_int = my_float;
    return 0; 
}

您对此有何解释?

最佳答案

关于c++ - 为什么 Clang 将显式强制转换解释为隐式强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25119370/

相关文章:

c++ - Eigen SparseLU 解决 error read access violation,this->m_sup_to_col was 0x111011101110112

c - 从二维 vector 数组进行直线拟合

c - For 循环未被执行 C

c++ - 直接在 foreach 循环中强制转换

java - 为什么我不能在 Java 中将(字节)数据类型转换为(短)数据类型

php - 展平二维数组并将所有字符串值转换为 int

c++ - std 命名空间中的 operator<< 有什么作用?

c++ - 如何在C++中动态分配数组

javascript - 如何使用 node.js 中的 c 头文件解析 UDP 数据包

c++ - 调用遗留 C API 时,如何在现代 C++ 中正确地将指向结构的指针转换为指向其他结构的指针?