我把出现的问题从项目中剥离了出来,然后再看,发现自己有点傻。
但因为项目中代码有点多,也是debug了一会儿才发现问题。
参考:
vs引发了异常: 读取访问权限冲突_qt vs 引发了异常: 读取访问权限冲突。 **other** 是 0x10。-CSDN博客
#pragma once
#include <QObject>
class QtClass : public QObject
{
Q_OBJECT
public:
QtClass(QObject *parent=nullptr);
void xxx();
~QtClass();
private:
int* x;
};
#include "QtClass.h"
QtClass::QtClass(QObject *parent)
: QObject(parent)
{
x = new int;
}
QtClass::~QtClass()
{}
void QtClass::xxx()
{
*x = 3;
}
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtWidgetsApplication1.h"
#include "QtClass.h"
class QtWidgetsApplication1 : public QMainWindow
{
Q_OBJECT
public:
QtWidgetsApplication1(QtClass *m,QWidget *parent = nullptr);
~QtWidgetsApplication1();
private:
Ui::QtWidgetsApplication1Class ui;
QtClass* c;
};
#include "QtWidgetsApplication1.h"
QtWidgetsApplication1::QtWidgetsApplication1(QtClass* m, QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
c = m;
c->xxx();
}
QtWidgetsApplication1::~QtWidgetsApplication1()
{}
错误写法:
#include "QtWidgetsApplication1.h"
#include <QtWidgets/QApplication>
#include "QtClass.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtClass* c;
QtWidgetsApplication1 w(c);
w.show();
c = new QtClass;
return a.exec();
}
因为x没有被new,因为c没有被new。
正确写法:
#include "QtWidgetsApplication1.h"
#include <QtWidgets/QApplication>
#include "QtClass.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtClass* c;
c = new QtClass;
QtWidgetsApplication1 w(c);
w.show();
return a.exec();
}