【问题标题】:An issue with QFile class nestingQFile 类嵌套的问题
【发布时间】:2013-09-25 06:06:06
【问题描述】:

当我定义如下结构时会出现问题

struct TInputData
{
    QString      filename;
    QFile        file;
    QTextStream  stream;
};

然后我将其放入 QVector 容器中,如下所示:

QVector<struct TInputData> input(DATA_SOURCE_END);

之后我调用了向量成员字段的一些方法:

for(int i = 0; i < DATA_SOURCE_END; ++i)
{
    input[i].filename = QString(argv[i + 1]);
    input[i].file.setFileName(input[i].filename);
    if (!input[i].file.open(QIODevice::ReadOnly))
    {
        QDebug(QtCriticalMsg) << "Failed to open input file: " << input[i].filename << "!!!";
        return a.exec();
    }
    input[i].stream.setDevice(&input[i].file);
    qDebug() << "Connected to input file " << input[i].filename;
}

我收到以下编译错误:

/usr/include/qt4/QtCore/qfile.h:209: error: 'QFile::QFile(const QFile&)' is private 
within this context <at line where struct TInputData is declared>

QTextStream 也是如此。

那么我错过了什么?

提前感谢您的帮助。

更新

@Ashot 提供的解决方案是手动创建 TInputData 对象。但它引入了一些额外的内存管理困难。解决方法是使用智能指针。

【问题讨论】:

  • 这意味着QFile 对象不可复制,这显然使它们难以放入向量中。如果您准备管理内存,则可以使用指针。某种智能指针将是最简单的答案。
  • 谢谢,我试试TInputData指针。

标签: c++ qt qfile qvector qtextstream


【解决方案1】:

QVector&lt;struct TInputData&gt; input(DATA_SOURCE_END); 更改为QVector&lt;TInputData*&gt; input(DATA_SOURCE_END);

QVector需要拷贝其内容,但QFile的拷贝构造函数是私有的,不能拷贝。

使用指针时,您应该手动新建和删除 TInputData 对象,或者您可以使用智能指针。

你可以试试QSharedPointerhttp://qt-project.org/doc/qt-4.8/qsharedpointer.html#QSharedPointer-2。 您的向量将是QVector&lt;QSharedPointer&lt;TInputData&gt; &gt; input(DATA_SOURCE_END)

【讨论】:

  • 非常感谢!您能否推荐一些信息(可能带有使用示例)来阅读有关智能指针的信息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 2010-09-28
  • 2012-05-04
  • 2021-01-16
相关资源
最近更新 更多