【发布时间】:2018-04-25 13:32:45
【问题描述】:
我有我的类对象,如果我在不同的地方有这个对象,当我删除并将这个对象初始化为 NULL 时,我希望这个对象在所有其他地方都是 NULL。有可能吗?
#include "mainwindow.h"
#include <QApplication>
#include "QDebug"
class A {
public:
int x;
int y;
};
class B : public A {
public:
B(int a, int b) {
this->m = a;
this->n = b;
}
int m;
int n;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
B* temp = new B(1, 2);
B* b1 = temp;
B* b2 = temp;
delete temp;
temp = NULL;
qDebug() << b1->x << b2->x; //its print 421312312 -2131231231
return a.exec();
}
【问题讨论】:
-
您需要的是智能指针。特别是共享和弱指针
-
如果你打算使用基于 Qt 的类,你需要的是
QPointer -
@DmitrySazonov 基于 QtObject 的类,否则正确。
-
@DmitrySazonov 不,我没有基于 Qt 的课程。我只有我的自定义类。
-
顺便说一句,您不需要
this->语法。直接赋值变量。