有什么方法可以调用析构函数来销毁对象吗?c++/smfl



在SFML中,我试图模拟一个游戏,我制作了一个Bullet类,在其中放置了一个destrucor函数。我想在按下按钮时销毁子弹,但当我按下它时,我的窗口冻结了,电脑kina崩溃了。有什么方法可以摧毁这个物体吗?我试着不画它,但它仍然在那里,只是看不见。

if (sf::Keyboard::isKeyPressed(sf::Keyboard::E)) bullet1.~Bullets();程序崩溃后的错误

你不能显式调用析构函数,但你可以得到相同的行为,在指针中有项目符号,并在其上调用delete。只需确保在任何delete之前始终有一个new,在每个new之前都有一个delete

// When declaring your variables
Bullets* bullet1 = nullptr; // don't call delete in this state
...
// In your bullet creation code
bullet1 = new Bullets();
...
// Delete the object and put pointer to null
delete bullet1; // Destructor will be called here
bullet1 = nullptr;
// When drawing it you must check if the object exists
if(bullet1 != nullptr){
window.draw(bullet1);
}

无论如何,正如评论中所说,在您对C++基础知识和OOP有了很好的理解之前,您不应该从SFML开始。

最新更新