c++ - 简单的引用变量赋值导致全局指针中的段错误?

标签 c++ vector segmentation-fault global-variables pass-by-reference

我在 .cpp 文件的第 15 行遇到段错误。我不确定为什么。各种代码片段: explosionhandler.h:

    class explosionhandler {
        public:
    struct explosion {
    ...
    };
    vector<struct explosion> explosions;
    struct explosion_type {
    ...
    };
    vector<struct explosion_type> type;
    int num_types;

    explosionhandler();
    ~explosionhandler();
    void registerexplosion(int& ttype,ALLEGRO_BITMAP*& b,int seq, float a, float m,float e);

    void createexplosion(int ttype,float x,float y);
    void drawexplosions(ALLEGRO_BITMAP* screen);

    void gettype(explosion_type& a,ALLEGRO_BITMAP*& b,int& nseq, float& aa, float& ee, float& mm);


        };#endif 

爆炸处理器.cpp:

    explosionhandler::explosionhandler()
    {
        num_types=0;
    }
    void explosionhandler::registerexplosion(int& ttype,ALLEGRO_BITMAP*& b,int seq, float a, float m,float e)
    {
        explosion_type n;
        ....
        ttype = num_types;     /*********** right here *******************/
        num_types++;
        type.push_back(n);
    }

explosionhandler 作为指向对象火箭的指针传递:

火箭.h:

...
class explosionhandler;
class rocket {
public:
        ...
        void setrocket(ALLEGRO_BITMAP*& a,ALLEGRO_BITMAP*& b, explosionhandler*& h);
        ...
        int exptype;
        ...
}; #endif

火箭.cpp:

rocket::rocket()
{
        ...
        exptype=-1;
}
void rocket::setrocket(ALLEGRO_BITMAP*& a,ALLEGRO_BITMAP*& b, explosionhandler*& h)
{
    handler = h;
    area.sethitboundaries(a);
    fprintf(stdout,"setrocket, # of rockets in vector: %i\n",(int)rockets.size());
h->registerexplosion(exptype,b,3,(float)al_get_bitmap_width(b),(float)0,(float)-18); //called function
}

最后是 main.cpp(缩写):

#include "rocket.h"
#include "explosionhandler.h"
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <stdio.h>
#include <cstdlib>
#define PI 3.14159265
...
rocket rock(bullet_speed+2,width,height);
explosionhandler *handler;
...
int setup()
{
        ...
        rock.setrocket(rk,exp,handler);
        rock.setlimit(5);
        al_set_target_bitmap(al_get_backbuffer(display));
        ...
}
...

好的,现在很清楚了,问题是处理程序没有初始化。哎呀。

当然 explosionhandler 是 main.cpp 中的指针,rocket 是 main.cpp 中声明的对象,两者都是全局变量。

保佑我的小菜鸟心,我不知道我在做什么。

最佳答案

我的心理感觉告诉我,您调用 rocket::setrocket 时使用 NULL 指针作为参数 h(或者更具体地说,是对 NULL 指针的引用), 然后你在 NULL 指针上调用 h->registerexplosion()

不要那样做。而是传入一个有效的指针,或分配一个新对象(确保稍后正确删除它)。

关于c++ - 简单的引用变量赋值导致全局指针中的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596948/

相关文章:

c++ - 请让我理解将派生类对象分配给基类指针- C++

c++ - BST 代码不适用于大数字

替换 R 中向量中多次出现的值

c - 如何正确地将内存分配给存储在结构中的动态整数数组?

c++ - 从 Spy++ 窗口获取文本

C++ init for循环内的多个类对象提供相同的内存地址?

c++ - 使用双端队列在 C++ 中实现循环缓冲区

vector - 如何将 Rust 书中的 "largest value in a Vec"示例转换为不使用 Copy 特性?

c - 使用数组时 C 中的段错误

c - 我是否正确地形成了这个多维数组?