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

error: conversion from 'QStringList' to non-scalar type 'QString' requested

本文关键字:标量 类型 QString QStringList 请求 错误 转换      更新时间:2023-10-16

这是我的类:

// 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'非标量类型

我哪里做错了?

在你的构造函数中,你接受一个参数的地址,当构造函数返回时该参数将消失:

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是指向QList<vector_t>的指针,所以cb_values[0]QList<vector_t>。所以cb_values[0]就是vector_t或者QVector<QStringList>。然后在这个向量上调用takeLast(),它返回QStringList,您尝试将其赋值给QString。在我看来,你正在调用takeLast()而不是你想要的对象