【问题标题】:QFileInfo exists() and isFile() errorQFileInfo exists() 和 isFile() 错误
【发布时间】:2014-07-18 19:20:53
【问题描述】:

我正在尝试检查提供的路径是否存在以及它是否是一个文件。
所以我写了这段代码:

#include <QFile>
#include <QFileInfo>


bool Tool::checkPath(const QString &path){
    QFileInfo fileInfo(QFile(path));
    return (fileInfo.exists() && fileInfo.isFile());
}

我得到以下编译器错误:

Error: request for member 'exists' in 'fileInfo', which is of non-class type 'QFileInfo(QFile)'

Error: request for member 'isFile' in 'fileInfo', which is of non-class type 'QFileInfo(QFile)'

为什么?我一遍又一遍地阅读文档,但我无法理解。 BTW Qt Creator 向我建议这些方法并完成它们。但是编译器不喜欢它。

【问题讨论】:

  • 为什么需要构造文件?只需使用 QFileInfo::QFileInfo(const QString & file) 构造函数。
  • 我刚刚错过了构造函数,但我看不出它应该造成任何伤害的原因。但它实际上在直接提供路径时有效。知道为什么吗?非常感谢您的解释。
  • 我认为编译器会处理 QFileInfo fileInfo(QFile(path));作为函数声明,而不是作为对象初始化。

标签: c++ qt file qfile


【解决方案1】:

好像vexing parse: 编译器认为

QFileInfo fileInfo(QFile(path));

是一个类似QFileInfo fileInfo(QFile path);的函数定义

改用类似的东西:

QFile ff(file);
QFileInfo fileInfo(ff);
bool test = (fileInfo.exists() && fileInfo.isFile());

【讨论】:

【解决方案2】:

可以直接使用

QFileInfo fileInfo(path)
bool test = fileInfo.exists() && fileInfo.isFile()

【讨论】:

    【解决方案3】:

    由于我的名声不好,我做不了cmets,所以在这里我放了一些关于QFileInfo的台词:

    QFileInfo fileInfo("./.py");
    bool test = fileInfo.exists() && fileInfo.isFile();
    

    那个例子会失败!

    我在检查中添加了 baseName() 值:

    bool test = fileInfo.exists() && fileInfo.isFile() && !fileInfo.baseName().isEmpty();
    

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多