получить объект перед его созданием, возможно ли это

#c

#c

Вопрос:

Возможно ли получить объект перед созданием самого объекта?

вот так

 template <class T>
class Event {
protected:
    T*Obj ; 
public:
    void onclick() { Obj->getobject()->dosomthing ; }  // i need help how to get the object
};

class myclass : public Event<myclass> {
public:
    Event<myclass>* getobject() {return Obj;}
    myclass* createobject() ; 
};
  

Я пробую несколько кодов и идей, но это всегда терпит неудачу, и я ничего не получаю (нулевой указатель)

Я пытаюсь указать на элемент и указатель на функцию, но это тоже не удается! Я не знаю, объясню ли я сейчас, чего именно я хочу.

Любая помощь?

Вот полный код

 template <class T>
class GUI_Event
{
private:
    static bool _Donothing (const EventArgs amp;Args) {return false ; }
    T*Obj ;

protected:

    /*for window only*/

    bool ( *CloseClicked )                     (const EventArgs amp;Args) ;
    /* event fired on left mouse click*/
    bool ( *_L_Mouse_Click_DoFunction )        (const EventArgs amp;Args) ;
    /* event fired on right mouse click*/
    bool ( *_R_Mouse_Click_DoFunction )        (const EventArgs amp;Args) ; 
    /*event  fired on middle mouse click*/
    bool ( *_M_Mouse_Click_DoFunction )        (const EventArgs amp;Args) ; 



public:



    /*set up fired function on left mouse click event*/

    const void Set_L_Mouse_Click_DoFunction( bool (*Function)(const EventArgs amp;Args))  {this->_L_Mouse_Click_DoFunction = NULL ; 
                                                                                           this->_L_Mouse_Click_DoFunction = Function ;
                                            Obj->Get_FrameWindowPtr ()->subscribeEvent ( FrameWindow::EventMouseClick , CEGUI::Event::Subscriber ( amp;_L_Mouse_Click_DoFunction ));} 

    /*set up fired function on right mouse event click */

};

class GUI_Window : public GUI_Event<GUI_Window>
{


private:


    static void SetID() ;
    /*
    Identifie Number For The Window
    */
    static int ID ; 

    /*
    /the Identifir Number for current window
    */
        int Wnd_ID ; 
        //Frame WIndow 
        CEGUI::FrameWindow        *_Frame_Window ;





        /* Window Name == value by the user */
        CEGUI::String             *_Window_Name ;


        /*window type == for now is inluded ( XML FIle (without extension)/FrameWindow )*/
        CEGUI::String             *_Window_Type;



        /* XML File that include style of the GUI   */
        String                    *_File_Name; 






public:

/*  create a Window */
        explicit GUI_Window ( CL_HUD const*Hud , String constamp;Window_Name );
        /*  create a Window */
        explicit GUI_Window ( const CL_HUD amp;Hud , String constamp;Window_Name );


    /*
    return current framewindow As Pointer 
    */
    FrameWindow              *const Get_FrameWindowPtr ()const                      { return _Frame_Window ; }
        /*
    return current framewindow 
    */
    const FrameWindow        amp;Get_FrameWindow ()const                               { return *_Frame_Window ; }





    /*return current window type*/
    const String            amp;Get_WindowType()  const                               { return *_Window_Type ;}
    /*return current window type As Pointer */
    String                  *const Get_WindowTypePtr()  const                      { return _Window_Type ;}



    /*return current window name As Pointer  */
    String                   *const Get_WindowNamePtr()  const                     { return _Window_Name ;}
    /*return current window name*/
    const String             amp;Get_WindowName()  const                              { return *_Window_Name ;}


    /* return XML File Name Scheme */
    const String             amp;Get_File_Name()  const                               { return *_File_Name ;}
    /* return XML File Name Scheme As Pointer */
    String                   *const Get_File_NamePtr()  const                      { return _File_Name ;}


    void SetText(String text )                        { Get_FrameWindowPtr ()->setText ( text ); *_Window_Name = text ; }
    int Get_ID ()                                                                  { return Wnd_ID ; }
    ~GUI_Window();


};
  

Проблема в том, что я получаю нулевой указатель в следующей строке

 Set_L_Mouse_Click_DoFunction
  

Комментарии:

1. Неясно, чего вы хотите достичь, на что четко указывают три разных ответа, которые у вас уже были. PS: Возможно, объяснение того, как вы будете это использовать, облегчило бы дать соответствующий ответ.

2. Публикация «стены кода» редко помогает получить лучшие ответы. Во всяком случае, это заставляет людей просто вообще пропустить вопрос. Попробуйте опубликовать небольшой фрагмент кода, который воспроизводит проблему. Иногда вы даже можете сами разобраться с проблемой, просто сделав это.

3. Google «Ленивая инициализация C » может обнаружить что-то полезное для вас, в противном случае вопрос мог бы потребовать уточнения и более краткого примера кода.

Ответ №1:

Длинный короткий ответ: Да. Но ваш объект не будет создан, поэтому, когда вы его «получите», он будет нулевым, и если вы его используете, вероятно, произойдут плохие вещи.

Короткий длинный ответ: Что?

 class Event
{
public:
bool onclick()
    { getobject->dosomthing ; }  //// getobject is a method.
                                 //// It should have parenthases
};

class myclass : public  Event
{
private:
Obj ;                  //// This is odd.  What is Obj?
                       //// Is it supposed to be a type or a variable name?
                       //// a line like the following would create the object on the stack:
                       //// myclass Obj;
 public:

  getobject() {return Obj;}
  createobject() ; 
};
  

Ответ №2:

Вы могли бы использовать наследование:

 class Event
{
public:
    virtual bool onclick() { /* default behavior here */ }
    virtual ~Event() { } // virtual destructor for a base class.
}

class MyClass : public Event
{
public:
    MyClass() { myObj = new Obj(); }

    bool onclick() { myObj->DoSomething(); }

    ~MyClass() { delete myObj; }
private:
    Obj* myObj;
}
  

Ответ №3:

Вы имеете в виду отложенную загрузку ваших объектов?

Ответ №4:

я отвечаю на свой вопрос следующим образом

 set_Object (T*newObj)     {Obj = newObj ; }
  

в GUI_Window я делаю

 set_Object(this)