1

我真的尝试了一切,但找不到解决方案,我尝试先初始化外部QVector然后初始化内部,但没有成功。

4

2 回答 2

2

QVector *matrix(作为类成员)带有新的?

这存在一些问题,即:

  • 您不应该QVector在堆上分配 a(即作为带有 new 的指针)。

  • 你应该使用QStringList更多。

我个人建议是这样的:

主文件

#include <QVector>
#include <QStringList>
#include <QDebug>

class Foo
{
    public:
        Foo() { qDebug() << matrix; }
    private:
        // Could be QStringLiteral, but you could also build it in the
        // constructor if it is dynamic
        QVector<QStringList> matrix{{"foo", "bar", "baz"}, {"hello", "world", "!"}};
};

int main()
{
    Foo foo;
    return 0;
}

主程序

TEMPLATE = app
TARGET = main
QT = core
CONFIG += c++11
SOURCES += main.cpp

构建并运行

qmake && make && ./main

输出

QVector(("foo", "bar", "baz"), ("hello", "world", "!"))
于 2014-12-14T11:20:20.630 回答
0

Probably you can't do this, because you missed one >. So try this:

#include<QDebug>
//...
private:
     QVector<QVector<QString> > *matrix = new QVector<QVector<QString> >;

And in constructor:

matrix->append(QVector<QString>() << "hello world");
qDebug() << "output: " << *matrix;

But I think that you should allocate memory in constructor. For example:

private:
     QVector<QVector<QString> > *matrix;

In constructor:

matrix = new QVector<QVector<QString> >;
matrix->append(QVector<QString>() << "hello world");
qDebug() << "output:" << *matrix;

Output in both cases:

output: QVector(QVector("hello world") )

于 2014-12-14T10:32:11.507 回答