c++ - 如何在我的实际类中访问另一个类的对象的实例?
问题描述
我将高分文件#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 类的方法中访问我的高分????我必须在头文件中做更多的事情吗?
解决方案
您的构造函数中有内存泄漏:
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* 计时器指针。
推荐阅读
- c# - 获取宿主程序数据的插件程序
- dart - 如何在颤动中将图像设置为壁纸?
- vb.net - VB.Net - 在组合框中显示是/否,但值为 1/0
- graph - 查找节点的邻居
- javascript - Wix中的d3 iframe?
- java - 有没有办法使用 Scanner 类 inputFile.nextLine()); 但是选择是随机的吗?
- php - PHP / MySQL,在这种特殊情况下不理解 foreach 循环。[概念Q]
- c# - 在 AWS Lambda 上使用 System.Drawing.Common NuGet 包时无法加载 DLL 'libdl'
- regex - 正则表达式正在一点点切割我的字符串
- java - Matriz em um AWT 帆布