QT变量赋值,<没有这样的值>,SIGSEGV

QT variable assignment, <no such value>, SIGSEGV

本文关键字:SIGSEGV gt 变量 赋值 lt QT      更新时间:2023-10-16

我有 3 个分类,每个分类都有 3 个 int 类型的变量。还有 3 个成员函数,我尝试将这些变量分配给动态数组并返回数组。在第一种情况下,一切都很好,当我尝试从第二类和第三类分配变量时,问题就会出现。

#ifndef TANK_H
#define TANK_H
#include <QObject>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
class Tank : public QObject, public QGraphicsPixmapItem
{
    Q_OBJECT
public:
    explicit Tank(QObject *parent = nullptr);
    void setTanks(int x, int y, QGraphicsScene * scene);
    void addTanks(int howMany = 0);
    int * showStatisticsOfTank();
protected:
    QGraphicsScene * scene;
    int coordinateX, coordinateY;
    int amountOfTanks;
    int attack;
    int defence;
    int cost;
signals:
public slots:
};
#endif // TANK_H

在.cpp文件中:

int *Tank::showStatisticsOfTank()
{
    int * arr = new int[3];
    arr[0] = amountOfTanks;
    arr[1] = attack;
    arr[2] = defence;
    return arr;
}

这行得通...但:

#ifndef WARPLANE_H
#define WARPLANE_H
#include <QObject>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
class Warplane : public QObject, public QGraphicsPixmapItem
{
    Q_OBJECT
public:
    explicit Warplane(QObject *parent = nullptr);
    void setWarplane(int x, int y, QGraphicsScene * scene);
    void addWarplane(int howMany = 0);
    int * showStatisticOfWarplane();
protected:
    QGraphicsScene * scene;
    int coordinateX, coordinateY;
    int amountOfWarplanes;
    int attack;
    int defence;
    int cost;
signals:  
public slots:
};
#endif // WARPLANE_H

在.cpp文件中:

int *Warplane::showStatisticOfWarplane()
{
    int * arr = new int[3];
    arr[0] = amountOfWarplanes; //HERE ERROR SHOWS UP
    arr[1] = attack;
    arr[3] = defence;
    return arr;
}

这不...SIGSEGV 错误出现,调试器在此行停止。当我试图查看战机数量,攻击和防御的价值时,它说:

<no such value>. 

第三类几乎相同,当我注释掉第二类错误时,第三类的错误出现在同一个地方。我试图清理所有 ->重建,不起作用。

SIGSEGV 在尝试访问 amountOfWarplanes 时发生,后者是 Warplane 类的内部成员。这意味着它在尝试访问此内容时发生。

这些条件表明战机指针无效。