QT创建者,返回(C++)

QT Creator, return (C++)

本文关键字:C++ 返回 创建者 QT      更新时间:2023-10-16

有人能解释一下为什么使用这两种类型的返回吗?

int parse(QTextStream& out, const QString fileName) {
    QDomDocument doc;
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
        out<<"Datei "<<fileName<<" nicht lesbar"<<endl;

>   return 1;
    }
    QString errorStr;
    int errorLine;
    if (!doc.setContent(&file, false, &errorStr, &errorLine)) {
        out<<"Fehler in Zeile "<<errorLine<<": "<<errorStr<<endl;

>  return 2;
    }
    ...
}

这是另一个节目的一部分。为什么这里的代码与的工作方式不同

返回0;

int main(int argc, char *argv[])
{
    QTextStream out(stdout);
       out.setCodec("UTF-8");
       if (argc != 3) {
           out<<"Usage: "<<argv[0]<<"   XML-Datei ist nicht vorhanden."<<endl;
           return(1);
       }
       List wayList(out, argv[1]);
       out<<"DOM-Baum gelesen."<<endl;
       wayList.convert(argv[2]);
return 1;
}

在第一个示例中,函数会提前返回以指示错误。无法打开该文件,因此函数会向该函数的调用方返回一个值。无法设置内容,函数向调用方返回了一个不同的值。

if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
    out<<"Datei "<<fileName<<" nicht lesbar"<<endl;
    return 1; // return value to caller
}

例如,函数可以调用parse并检查其返回值是否成功:

if ((parse(args...)) == 0) // success

在函数main()的末尾,return 0;表示程序运行成功。