如何在它们之间分配和使用 2 个不同类的函数指针?



我正在开发一个协议栈,我已经用类编写了一个不同的级别,它们具有用于连接它们之间不同级别的函数和函数指针。

我在管理和分配函数指针方面遇到问题。情况类似于以下内容(简化(:

文件库A.h:

class baseA
{
public:
virtual void fnc1(void)=0;
void (B::*fnc2)(void)=NULL;
};

文件A.h:

class A:baseA
{
public:
void task(void);
void fnc1(void);
void (B::*fnc2)(void)=NULL;
};

文件 A.cpp:

void A::task()
{
if(this->fnc2!=NULL)
this->fnc2();
}
void A::fnc1(void)
{
//Do something
}

文件B.h:

class B
{
public:
void task(void);
void fnc1(void);
void (baseA::*fnc2)(void);
};

文件 B.cpp:

void B::task(void)
{
if(this->fnc2!=NULL)
this->fnc2();
}
void B::fnc1(void)
{
//Do something
}

主要功能:

main(void)
{
A instA;
B instB;
instA.fnc2 = instB.fnc1;
instB.fnc2 = instA.fnc1;
while(1)
{
instA.task();
instB.task();
}
}

我有两个问题:

  1. 在函数main中,当我分配函数指针时,编译器返回错误"cannot convert 'B::fnc1' from type 'void (B::)()' to type 'void (*)()'"(对于instA.fnc2 = instB.fnc1;(和"cannot convert 'A::fnc1' from type 'void (A::)()' to type 'void (*)()'"(对于instB.fnc2 = instA.fnc1;(。
  2. 当我使用函数指针时,在task函数内,编译器返回错误"must use '.*' or '->*' to call pointer-to-member function in '((A*)this)->A::fnc2 (...)', e.g. '(... ->* ((A*)this)->A::fnc2) (...)'"。我尝试使用(this->*fnc2)();但在这种情况下,编译器返回错误"pointer to member type 'void (B::)()' incompatible with object type 'A'">

我试图搜索并应用在互联网上找到的不同建议,但我无法解决问题。 我的错误是什么?

成员函数指针语法不是微不足道的,但你在这里有一个主要的理解问题:它是指向给定类的方法的东西。这意味着:

  1. 加载它时引用类而不是(可能是多态(对象
  2. 在其类的对象上调用它

首先很简单,你必须在你的主中使用它:

instA.fnc2 = &B::fnc1;
instB.fnc2 = &baseA::fnc1; // and not A::fnc1 since fnc1 is only declared in baseA

对于第二点,您将需要A中的B对象(或引用或指针(和B中的A对象(或引用或指针(。为简单起见,我将在此处使用指针:

class A:baseA
{
public:
void task(void);
void fnc1(void);
void (B::*fnc2)(void)=NULL;
B* b;
};
void A::task()
{
if(this->fnc2!=NULL && b != NULL)
(b->*fnc2)();    // note the parentheses to avoid a syntax error
}
class B
{
public:
void task(void);
void fnc1(void);
void (baseA::*fnc2)(void);
A* a;
};
void B::task(void)
{
if(this->fnc2!=NULL && a != NULL)
(a->*fnc2)();
}

最新更新