Example of callback function and function pointer in C++
- 2020-06-01 10:25:41
- OfStack
Example of callback function and function pointer in C++
How to get a function pointer in a class
Implementation code:
//A Class and B The definition of a class
class A
{
public:
void Test()
{
cout << "A::Test()" << endl;
}
};
class B : public A
{
public:
void Test()
{
cout << "B::Test()" << endl;
}
};
// Defines a pointer to a member function of a class
typedef void (A::*A_mFun)(void);
typedef void (B::*B_mFun)(void);
int main()
{
//Code
A a;
B b;
A_mFun pAFun = &(A::Test); //Note:Test The member function must be public, Otherwise you'll get an error
B_mFun pBFun = &(B::Test); //Note:Test The member function must be public, Otherwise you'll get an error
(a.*pAFun)(); // The output A::Test()
(b.*pBFun)(); // The output B::Test()
(b.*pAFun)(); // The output A::Test()
A* pA = &a;
B* pB = &b;
(pA->*pAFun)(); // The output A::Test()
(pB->*pBFun)(); // The output B::Test()
(pB->*pAFun)(); // The output A::Test(),B* A variable can be assigned to A* variable
return 0;
}
If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!