【问题标题】:Issues with qDebug and QString const referenceqDebug 和 QString const 参考的问题
【发布时间】:2012-02-16 04:00:01
【问题描述】:

有一个具有以下功能的类:

FileInfoWrapper(const QFileInfo &_fileInfo) : fileInfo(_fileInfo) {}

const QString& FileName() const { return fileInfo.fileName(); }

但是当我这样做时:

QFileInfo info(somePath);

qDebug() << info.absoluteDir(); // works

FileInfoWrapper test(info);

qDebug() << test.FileName(); // this crashes the entire application

当我从字符串返回中删除 const & 时,它可以工作。就像

【问题讨论】:

    标签: c++ qt qstring qdebug


    【解决方案1】:

    您返回对 QString 的引用,该引用在您离开 FileName() 函数时被销毁。

    【讨论】:

      【解决方案2】:

      std::cout 不知道 QString,你需要将其转换为 std::string 或 const char*

      使用QString::toStdString 转换为std::string,例如:

      std::cout << test.FileName().toStdString();
      

      【讨论】:

      • 哦,对不起。我提到了处理 qstrings 的 qDebug,但显然没有引用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2017-12-12
      相关资源
      最近更新 更多