我想要实现的基本思想是从B类调用A类的方法,反之亦然。 这是我的代码:
的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();
};
从上面的代码中,我想知道:
干杯, 维尼特。
答案 0 :(得分: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();
}