如何在实际类中访问另一个类的对象的实例

How can I access the instance of an object of another class in my actual class?

本文关键字:另一个 对象 实例 访问      更新时间:2023-10-16

我 #included 高分文件到我的头上。 现在我正在我的潜艇.cpp中创建它的对象,但无论如何我都无法访问它。当我尝试写"highscore."来向我展示它的一些方法时,它没有显示任何内容,并告诉我我之前声明的变量未使用。

Submarine::Submarine(QGraphicsItem* parent):QObject (),         
QGraphicsPixmapItem (parent)
{
Highscore *highscore = new Highscore;
QTimer * timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(die()));
timer->start(50);
}
void Submarine::doSomething()
{
highscore->increase(); (HERE)

我怎样才能在我的潜艇课程的方法中获得我的高分????我必须在头文件中做更多的事情吗?

构造函数中有内存泄漏:

Submarine::Submarine(QGraphicsItem* parent):QObject (),         
QGraphicsPixmapItem (parent)
{
Highscore *highscore = new Highscore; // <-- Your problem is here
QTimer * timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(die()));
timer->start(50);
} // <-- the highscore and timer pointers go out of scope here

在构造函数的末尾,指向 Highscore 实例的指针超出范围并丢失。 您需要将其保存在 Submarine 类的成员变量中,以便随后在 doSomething() 方法中使用它。 同样的问题适用于在构造函数主体中创建的 QTimer* 计时器指针。

相关文章: