首页 > 解决方案 > 如何在我的实际类中访问另一个类的对象的实例?

问题描述

我将高分文件#included 到我的标题中。现在我正在我的subsub.cpp 中创建它的一个对象,但无论如何我都无法访问它。当我尝试时,写“高分”。为了向我展示它的一些方法,它没有显示任何内容,并告诉我我之前声明的变量未使用。

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 类的方法中访问我的高分????我必须在头文件中做更多的事情吗?

标签: c++object

解决方案


您的构造函数中有内存泄漏:

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* 计时器指针。


推荐阅读