c++ - 从 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 (...)
{
}
}
解决方案
就是这样。谢谢@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
推荐阅读
- powerquery - 在 SQL 中使用 Text.Combine 字符串作为参数时出现错误“无法将字段访问应用于文本类型”
- numpy - 加快计算高斯概率密度的numpy矩阵乘法的方法
- java - 传递 ArrayList 的特定索引
但 String 实际上是一个 String[][] - mysql - MySQL 如何从具有多个条件的单个匹配表中进行选择(AND / OR 不起作用)?
- javascript - 输入所需数字时的 HTML 事件处理程序
- java - 如何制作一个像这个自定义对话框这样的对话框选择框,右上角的取消按钮像这样?
- amazon-web-services - AWS EC2 使用 AWS 服务(如 cron 作业)调度 python 文件
- python - 我如何在 python 代码中使用基于 python 的项目及其命令行
- java - 打印 ArrayList 的值
> 不包含在另一个 ArrayList 中 > - wxpython - wxpython:如何从导入的脚本中使用 SetLabel 更新面板文本?