我试图访问另一个类中声明的类的成员作为属性。
项目类有一个workArea,它也是project.h中定义的类。
我在main中实例化一个项目,然后通过它的构造函数将它发送到mainWindow。进入mainWindow构造函数后,我尝试访问project-> lat工作正常,但project-> workArea-> latInf崩溃。
任何帮助都将受到高度赞赏。
project.h
#ifndef PROJECT_H
#define PROJECT_H
#include <QObject>
class WorkArea{
public://attributes
int latInf = 30;
public://methods
WorkArea()//Default constructor
{
}
~WorkArea();
};
class Project : public QObject
{
Q_OBJECT
public: //attributes
int lat = 20;
WorkArea* workArea;
public: //methods
explicit Project(QObject *parent = nullptr);
signals:
public slots:
};
#endif // PROJECT_H
的main.cpp
#include "ui/mainwindow.h"
#include <QApplication>
#include "project.h"
int main(int argc, char *argv[])
{
Project* pj;
QApplication app(argc, argv);
MainWindow w( 0 , pj);
w.show();
return app.exec();
}
mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent, Project *project) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
try
{
qDebug() << "Project latInf" << project->lat << "\n"; // works fine
qDebug()<< "Project lowLeft: " << project->workArea->latInf << "\n" ; // crashes
}
catch(std::exception &ex)
{
qDebug() << ex.what() ;
}
catch (...)
{
}
}
答案 0 :(得分:1)
就是这样。谢谢@eyllanesc。我忘了创建workArea。我只是将它作为Project中的属性进行实例化很好,但我必须在项目的构造函数中填充该内存空间。
<强> project.h 强>
#ifndef PROJECT_H
#define PROJECT_H
#include <QObject>
class WorkArea{
public://attributes
int latInf = 30;
public://methods
WorkArea()//Default constructor
{
}
~WorkArea();
};
class Project : public QObject
{
Q_OBJECT
public: //attributes
int lat = 20;
WorkArea* workArea;
public: //methods
explicit Project(QObject *parent = nullptr){
workArea = new WorkArea;
}
signals:
public slots:
};
#endif // PROJECT_H