返回 bool 的函数即使返回 1 或 0 也能工作

function returning bool works even though it returns 1 or 0

本文关键字:返回 工作 bool 函数      更新时间:2023-10-16
bool CWaypoint::less(CWaypoint const &wp_right)
{
    bool result;
    CWaypoint temp1;
    (calculateDistance(temp1) > temp1.calculateDistance(wp_right)) ?
            result = 1 : result = 0;
    return result;
}

为什么即使我不返回布尔类型也不会收到错误?

发生整数到布尔值的转换。从C++标准:

4.12 布尔转换 [conv.bool]

算术、无作用域枚举、指针或指向成员类型的指针的 prvalue 可以转换为布尔类型的 prvalue 值。零值、空指针值或空成员指针值将转换为 false;任何其他值都将转换为 true