【问题标题】:error: conversion from 'QStringList' to non-scalar type 'QString' requested错误:请求从“QStringList”转换为非标量类型“QString”
【发布时间】:2014-07-21 15:42:33
【问题描述】:

这是我的课:

// file .h
#ifndef UNDOREDO_H
#define UNDOREDO_H

#include <QUndoCommand>

typedef QVector<QStringList> vector_t ;

class UndoRedo : public QUndoCommand
 {
 public:
     UndoRedo(QList<vector_t> v,
                    QUndoCommand *parent = 0);

     void undo();
 private:    
     QList<vector_t> *cb_values;
 };

#endif // UNDOREDO_H
// file .cpp
#include "undoredo.h"

UndoRedo::UndoRedo(QList<vector_t> v,
                   QUndoCommand *parent)
    : QUndoCommand(parent)
{
    cb_values = &v;
}

void UndoRedo::undo() {    
    QString last = cb_values[0][0].takeLast();
    qDebug() << last << "removed!";
}

当我调用 undo() 方法时,IDE 会引发此错误:

错误:请求从“QStringList”转换为非标量类型“QString”

我哪里做错了?

【问题讨论】:

    标签: c++ qt qtcore qlist qvector


    【解决方案1】:

    在您的构造函数中,您获取的参数地址将在构造函数返回时消失:

    cb_values = &v;
    

    这行代码会编译,但它是荒谬的。一旦构造函数返回,存储在cb_values 中的指针就会悬空,进一步使用它可能会导致您的硬盘被格式化。

    让我们分解cb_values[0][0].takeLast()。

    QList<vector_t> * cb_values
    QList<vector_t> cb_values[0]
    QVector<QStringList>=vector_t cb_values[0][0]
    QStringList cb_values[0][0].takeLast()
    

    所以,您的表达式类型是QStringList,但您正试图将其分配给QString。我不知道你真正想要达到什么目的。也许(*cb_values)[0][0].takeLast()?

    【讨论】:

    • 是的,就是 (*cb_values)[0][0].takeLast()
    【解决方案2】:

    cb_values 是指向QList&lt;vector_t&gt; 的指针,所以cb_values[0] 是QList&lt;vector_t&gt;。所以cb_values[0] 是vector_t,或者QVector&lt;QStringList&gt;。然后你在这个向量上调用takeLast(),它返回QStringList,你尝试将它分配给QString。在我看来,您调用 takeLast() 不是在您想要的对象上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      相关资源
      最近更新 更多