How to pass pointer of class member function __ Programming Technology

Source: Internet
Author: User

Demand:

In Class A, there is a set of functions with the same specification;

Class B has a pointer to member F in a member function, initializes the member F when constructing a B object, and then calls the function of the function pointer in the DO function.

What needs to be done to achieve this goal.

Class A

Void F1 ();

Void F2 ();

Void F3 ();

Class B

B (f)

Do ()

{

F ();

}

F

A * PA;

One feature of C + + is needed here: a member function pointer. This feature is generally rarely used, so the feeling is more obscure, using the following points:

1. Use a typedef to define the type of a member function pointer:

typedef void (A::* FunC) ();

This defines the Func as a null return value type in Class A and a null function pointer for the argument list.

2. Statement in B

FunC F;//To declare F as a pointer to a member function in a.

3. Declare the constructor of B

B (* A, Func f) {PA = A; f = f;}

4. Do in the following call:

(pa->*f) ();

5. Externally constructs a, B objects, and makes method calls.

A A;

B B1 (&a, &A::F1);

B1.  Do (); This will call the F1.

B B2 (&a, &A::F2);

B2.  Do (); This will call the F2.

Special Note:

C + + member functions implicitly have a this argument, that is, to invoke the Class object's member function, you must first have the object of the class, and therefore, in B's constructor to pass a object address in.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.