【问题标题】:How can I initialize QVector<QVector<QString>> *matrix (as class member) with new?如何用 new 初始化 QVector<QVector<QString>> *matrix (作为类成员)?
【发布时间】:2014-12-14 10:29:18
【问题描述】:

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

【问题讨论】:

    标签: c++ qt qstring qtcore qvector


    【解决方案1】:

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

    这有问题,即:

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

    • 你应该更多地使用QStringList

    我个人的建议是这样的:

    main.cpp

    #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;
    }
    

    main.pro

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

    构建并运行

    qmake && make && ./main
    

    输出

    QVector(("foo", "bar", "baz"), ("hello", "world", "!"))
    

    【讨论】:

    • 你能用 1 或 2 句话解释一下,为什么“你不应该在堆上分配 QVector”吗?谢谢
    • @SimonWarta:因为它使代码更复杂而没有太多收益恕我直言,尤其是 QVector 是 CoW。谢谢。
    【解决方案2】:

    可能你不能这样做,因为你错过了一个&gt;。所以试试这个:

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

    在构造函数中:

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

    但我认为你应该在构造函数中分配内存。例如:

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

    在构造函数中:

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

    两种情况下的输出:

    输出:QVector(QVector("hello world"))

    【讨论】:

    • 你编译了那个代码吗?你真的可以在标题中创建一个带有 new 的对象吗?这不就是初始化列表的用途吗?
    • @SimonWarta 是的,它可以编译,为什么不呢? ideone.com/WkkCaV 也许旧的编译器不支持这个。但无论如何我在回答中说我建议在构造函数上分配内存(当然我们可以使用初始化列表,但不禁止直接在构造函数中分配内存)。
    • 你是对的,只要你使用指针或副本但不使用非标准构造函数,它就可以工作:ideone.com/mbGOvz
    • @SimonWarta: it is a C++11 feature.
    猜你喜欢
    • 2013-05-21
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2020-06-10
    • 2021-02-20
    • 2019-03-02
    相关资源
    最近更新 更多