提问者:小点点

将类型<t>转换为bool,有什么问题吗?


以下代码没有按预期工作:

template<class T>
bool any(const Matrix<T> &matrix) {
    int matrix_height = matrix.height();
    int matrix_width = matrix.width();
    for (int i = 0; i < matrix_height; i++) {
        for (int j = 0; j < matrix_width; j++) {
            if (matrix(i, j) == true) {
                return true;
            }
        }
    }
    return false;
}

对于像{-1,0,0,0}这样的矩阵,有一个成员-1,它是真的,所以它应该返回true,但它返回false。 我把T值转换成布尔值的方式是不是错了?


共1个答案

匿名用户

要检查条件是否为truth(y),可以使用if(condition)。 它将表达式计算为布尔值。 因此if(7)的计算结果为if((bool)7),这确实是正确的。 另一方面,

if(7 == true)

计算数值相等,将true向上强制转换为整数,并将其与7进行比较。 在我熟悉的大多数实现中(所有?) true==1,因此它的计算结果为7==1。 这里(通常)产生true的唯一数字是1