首页 > 解决方案 > 从 C++ 中的另一个类访问类成员

问题描述

我正在尝试访问在另一个类中声明为属性的类的成员。

项目类有一个 workArea,它也是 project.h 中定义的一个类。

我在 main 中实例化一个项目,然后通过它的构造函数将它发送到 mainWindow。一旦进入 mainWindow 构造函数,我尝试访问 project->lat 工作正常,但 project->workArea->latInf 崩溃。

任何帮助将不胜感激。

项目.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

主文件

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

主窗口.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 (...)
    {

    }
}

标签: c++qtpointersexception

解决方案


就是这样。谢谢@eyllanesc。我忘了创建工作区。我虽然只是将它作为 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

推荐阅读