【问题标题】:Deleting global object in game.(C++)删除游戏中的全局对象。(C++)
【发布时间】:2013-05-02 11:18:29
【问题描述】:

我正在用 C++ 制作一个泡泡爆破游戏,用户点击随机生成的漂浮在屏幕上的泡泡(仍在开发中)。为了在这个游戏中使用 OpenGl 和 Glut,我发现最好让我的 Bubbles 全球化。我有一个空白析构函数,但我不知道如何删除 Bubble 的内容并创建一个新的。我尝试使用动态分配,但没有任何区别。如何删除 Bubble 的内容并创建一个新的?

这是一个必要的sn-p:main.cpp

Bubble myBubble1; void display(void) {
delete myBubble1;//error "cannot delete type Bubble" 
}

我的析构函数在这里:

class Bubble { 
  public:
 //default constructor

 Bubble()
 {

     radius=(rand() % 100 )+1;
     speed = rand() % 500 ;
     xVal = rand() % 480;
     yVal= -14;
     isLive=true;

 }
 ~Bubble()
 {

 } 
private:

 float radius;
 float speed;
 float xVal;
 float yVal;
 bool isLive;
};

当我不尝试删除任何内容时,代码运行良好。我可以无限循环泡泡

【问题讨论】:

  • 帮助记住:任何时候使用new,都应该有一个对应的delete。如果您从不使用new,则您没有什么可手动删除。请参阅stackoverflow.com/q/716353/1751715 之类的问题,它是重复的以获取更多信息。注: ~ 每个删除都必须在它自己的 delete thingy; 行上。你不能写delete thing1, thing2, thing3;;见stackoverflow.com/q/3037655/1751715

标签: opengl global-variables destructor glut


【解决方案1】:

您没有在 Bubble 中使用任何指针,因此您的析构函数可以保持空白。如果你想重新分配你的Bubble 就这样

Bubble myBubble1;
//use myBubble1
...
myBubble1 = Bubble();

【讨论】:

    【解决方案2】:

    如果您在这样的范围内声明 Bubble

    void func()
    {
        Bubble b;
    }
    

    它会在你退出func() 的作用域后立即销毁。 (RAII)

    您需要使用delete 的唯一时间是手动为Bubble 分配内存并且只能对指针执行此操作:

    void func()
    {
        Bubble* b = new Bubble;
    
        delete b;
    }
    

    如果要随意删除,将其声明为指针(首选std::unique_ptr之类的智能指针),随意删除。 (或smartPointer.reset()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多