如何在创建实例时将实例本身传递给外部地图?

时间:2015-06-19 06:48:11

标签: c++ dictionary constructor instance

我有一个Object类和一个typedef:

class Object
{
private:
    long int id;
public:
    Object(void);
    ~Object(void) {};
    long int get_id(void);
};

typedef map<long int, Object> obj_map;

然后我有这个类App,它有一个obj_map和object_counter:

class App
{
public:
    static ALLEGRO_DISPLAY *display;
    static ALLEGRO_EVENT_QUEUE *event_queue;
    static ALLEGRO_TIMER *timer;
    static ALLEGRO_EVENT e;
    static bool running;
    static bool redraw;
    static key_map key_states;
    static obj_map objects; // << Here.
    static long int object_counter; // << Here.
    const char *window_title;
    int screen_width;
    int screen_height;
    float FPS;
    act event_scenes;
    act visual_scenes;
    ALLEGRO_COLOR background_color;

    static ALLEGRO_EVENT event();
    static ALLEGRO_EVENT_TYPE event_type();
    static void shut_down();

    App(int screen_width, int screen_height, const char *window_title = "Joy++ Application", float FPS = 30);
    ~App() {};

    int init_all();
    void register_all();
    void check_key_states();
    void init_key_states();
    void run();
    void destroy_all();
    void add_event_scene(Scene scene);
    void add_visual_scene(Scene scene);
    void remove_event_scene(Scene scene);
    void remove_visual_scene(Scene scene);

    long int get_object_count();
    unsigned int get_random_int(unsigned int min, unsigned int max);
    void set_key_state(int al_key, string key_name, bool state);
    void set_background_color(int r, int g, int b);
};

正如您所看到的,我们的想法是将应用程序内的每个对象存储在地图内的ID下。但是,我希望在创建每个对象的那一刻发生这种情况。所以这里是构造函数定义:

Object::Object()
{
    App::object_counter += 1;
    this->id = App::object_counter;
    App::objects[this->id] = this; // Problem.
}

错误:

G:\Development\Game-Development\CB\Joy-Plus-Plus\app.cpp|26|error: no match for 'operator=' (operand types are 'std::map<long int, Object>::mapped_type {aka Object}' and 'Object* const')|

如何在创建时将每个Object的实例本身传递给外部地图?

2 个答案:

答案 0 :(得分:1)

如果您的对象具有语义值,则只需指定*this(对象)而不是this

另一方面,如果身份计数然后构建一个映射到Object *(或更好的std :: shared_ptr),然后赋值将按原样运行

答案 1 :(得分:0)

因为这是指针类型 - &gt;试试* this

您想在地图中存储copys还是仅仅引用对象?