QDEBUG和QSTRING CONST参考的问题
题
具有具有以下功能的课程:
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&时,它可以正常工作。就像<<不适合参考。怎么了,为什么会崩溃?
解决方案
您返回对QSTRING的引用,该QString在您离开filename()函数时被破坏。
其他提示
std :: cout不知道qString,您需要将其转换为std :: string或const char*
利用 QString::toStdString
转换为std :: string,例如:
std::cout << test.FileName().toStdString();
不隶属于 StackOverflow