2016-03-14 4 views
0

Основная идея, которую я пытаюсь реализовать, - это метод вызова класса A из класса B и наоборот. Вот мой код:Коммуникация 2 пути между классами в C++

main.cpp

void AppCB (uint8_t num, TempB* inst){ 
    printf("Application Level Callback Called!!!\n"); 
} 

void main(int, char*[]) { 
    printf("Starting Up!!!\n"); 
    TempB instB(1, funcptr_arg1 (&AppCB)); 
    instB.funcB(); 
} 

callback.cpp

void TempA :: tempa_cb (void){ 
    printf("Calling Callback to B\n"); 
    tempBobj->funcB_cb(); 
} 

void TempA :: funcA(){ 
    // some delay 
    tempa_cb(); 
} 

void TempA :: registerTempB (TempB *tempbobj){ 
    this->tempBobj = tempbobj; 
} 
TempB :: TempB (uint8_t num , funcptr_arg1 AppCallback){ 
    printf("Constructor TempB\n"); 
    slot = num; 
    funtptrB = AppCallback; 
    instA.registerTempB(this); 
} 

void TempB :: funcB(){ 
    instA.funcA(); 
} 

void TempB :: funcB_cb(){ 
    printf ("Call from TempA\n"); 
    this->funtptrB(event, this); // <<<<<<<<<<<< this pointer is corrupted here. Hence it is not able to call the AppCB function in main.cpp file. 
} 

callback.h

typedef void (*funcptr_arg1)(int, void *); 

class TempB; 

class TempA { 
    private: 
     uint8_t tempa; 
     TempB *tempBobj; 

    public: 
     void funcA(); 
     void tempa_cb(void); 
     void registerTempB (TempB *tempbobj); 
}; 
class TempB { 
    private: 
     uint8_t slot; 
     funcptr_arg1 funtptrB; 
     TempA instA; 

    public: 
     TempB (uint8_t num, funcptr_arg1 funtptrB); 
     void funcB(); 

     // this function should be called from object of A. 
     void funcB_cb(); 
}; 

Из приведенного выше кода, я хотел бы знать:

  1. Почему «это» указатель (он используется для вызова функции) поврежденным, как отмечено в коде?
  2. Есть ли лучшее для этого?

Cheers, Vineet.

+0

Вы никогда не должны использовать C-указатели функций в программе на C++, если вам не нужно связываться с устаревшим кодом C, который требует этого. Эти экземпляры классов должны связываться друг с другом через указатели классов. – pasztorpisti

+0

Были бы проблемы с глубинными функциями. Я впервые слышу об этом. – xvan

+0

Спасибо за информацию. Я новичок в C++. Поэтому, исследуя наилучший вариант :-) – Jain

ответ

0

Ниже приведен пример C++ для взаимодействия экземпляров двух классов. Я не компилируется и протестировал код, написанный только в браузере, но это достаточно описательный, чтобы дать вам идею:

dummy.h:

// This forward declaration will allow us to use B pointers 
// in the declaration of class A, but it will not allow to 
// access its members. For this reason the methods of A that 
// want to access the members of B must be defined after the 
// declaration of class B. 
class B; 

class A 
{ 
public: 
    A(B* b): m_B(b) {} 
    void CalledByB() {} 
    void PerformWork(); 

private: 
    B* m_B; 
}; 

class B 
{ 
public: 
    void SetA(A* a) { m_A = a; } 
    void CalledByA() {} 
    void PerformWork(); 

private: 
    A* m_A; 
}; 

dummy.cpp:

#include "dummy.h" 

// Since we already included the declaration of class B by 
// including dummy.h we can start using the members of B 
// through the m_B pointer. By defining this method as an 
// inline in the declaration of class A we couldn't have 
// called m_B->CalledByA() because at that point the declaration 
// of class B was unavailable. 
void A::PerformWork() 
{ 
    m_B->CalledByA(); 
} 

// In case of class B we could have put this code to the header 
// too because we declared class B after class A so at the time 
// of the declaration of B the full declaration of A was available 
// for the compiler. 
void B::PerformWork() 
{ 
    m_A->CalledByB(); 
} 

int main() 
{ 
    // Initialization 
    B b; 
    A a(&b); 
    b.SetA(&a); 

    // Work 
    a.PerformWork(); 
    b.PerformWork(); 
} 
+0

Спасибо за ваш ответ. Я предполагаю: A a ( b.SetA (&a); можно назвать внутри класса B, так как я не хочу выставлять их на главную? – Jain

+0

@VineetGolchha Конечно, вы можете поместить код инициализатора в другое место. – pasztorpisti

Смежные вопросы