We will define member functions in the class, and we also want to define member function pointers. Therefore, we need to solve three problems: first, how to define the class function pointer, second assignment, and third use.
I define a class,
Class
{
Public:
Int add (int, int );
Int mul (int, int );
Int div (int, int );
};
Int A: add (int a, int B)
{
Return a + B;
}
Int A: mul (int a, int B)
{
Return a * B;
}
Int A: div (int a, int B)
{
Return (B! = 0? A/B: );
}
I want to define A pointer that points to the function pointer with the return value of type A being int and the parameter being two int. Students familiar with C will immediately write typedef int (* pair) (int, int ). However, this problem occurs when C ++ is used,
As we know, the non-static member method of the class actually has the parameter of this pointer. For example, the add method may actually define int add (A * this, int a, int B). Therefore, we cannot simply move the set of items in the C language, we need to redefine this type of pointer. The correct method is to add the type, typedef int (A: * Action) (int, int)
Typedef int (A: * Action) (int, int );
Int main ()
{
A;
Action p = & A: add;
Cout <(a. * p) (1, 2) <endl;
Return 0;
}
Action p = & A: add; this is the value assignment statement.
Note that this (* p) () cannot be used directly, and it must be bound to an object (. * p) (); we can also define the class function pointer in the class declaration.
Class
{
Public:
Int add (int, int );
Int mul (int, int );
Int div (int, int );
Int (A: * random) (int, int );
};
The above method is for non-static member functions. How should I define the function pointer of the static member function? Can I use the above method? We know that the static member function does not have the this pointer, so it does not add class restrictions. Its function pointer definition method is the same as the function pointer definition method in C.
Class
{
Public:
Int add (int, int );
Int mul (int, int );
Int div (int, int );
Static int sub (int, int );
};
Int A: sub (int a, int B)
{
Return a-B;
}
Int main ()
{
Int (* pp) (int, int) = & A: sub;
Cout <(* pp) (10, 5) <endl;
Return 0;
}
To sum up, the class name must be added to the function pointer of a non-static member function. The function pointer of a static member function is the same as that of a common function.
Note that
If the function pointer is defined in a class, it is slightly different when called.
Class
{
Public:
Int add (int, int );
Int mul (int, int );
Int div (int, int );
Int (A: * pfunc) (int, int );
}; Www.2cto.com
Int main ()
{Www.2cto.com
A;
A. pfunc = & A: add;
Cout <(a. * (a. pfunc) (1, 2) <endl;
Return 0;
}
Author: yg2133