类型自动转换引起的误解——QString可以赋值数字1,也能直接与0比较,真是昏倒!

看以下代码,能编译通过:

void MainWindow::on_pushButton_clicked()
{
    QString str = "test";
    if (str==0) {
        QMessageBox msgBox;
        msgBox.setText("The document has been modified.");
        msgBox.exec();
        str = 1;
    }
}

编译通过,我还以为自己看错了。专门做了一个Demo,结果还是编译通过。

后来找到了理论解释,就是使用了重载,其参数通过自动转换获得:

QString & operator=(const char *str)
bool operator==(const char *other) const

-------------------------------------------------------------------------------

但是如果改成 if (str==1) 却又编译不过了,原因如下:

我刚刚写1了,所以编译报错了
0就是NULL
所以11里加了个nullptr
NULL应该淘汰了

原文地址:https://www.cnblogs.com/findumars/p/5317793.html