Home > Backend Development > C++ > How Do I Call a Pointer to a Member Function in C ?

How Do I Call a Pointer to a Member Function in C ?

Linda Hamilton
Release: 2024-12-05 15:45:10
Original
251 people have browsed it

How Do I Call a Pointer to a Member Function in C  ?

C Calling a Pointer to a Member Function

Calling a pointer to a member function in C requires specific syntax. Here's the anatomy of the syntax:

(*pointer_to_member_function)(object_pointer, arguments);
Copy after login

Example 1: Calling a Member Function with a Pointer

Consider the code snippet:

typedef void (Box::*HitTest) (int x, int y, int w, int h);

for (std::list<HitTest>::const_iterator i = hitTestList.begin(); i != hitTestList.end(); ++i)
{
    HitTest h = *i;
    (*h)(xPos, yPos, width, height);
}
Copy after login

Here, hitTestList is a list of pointers to member functions named HitTest. To call each member function using its pointer, you need to specify the this pointer, which refers to the object the function is called on. In this case, you have a pointer to a Box object box, which you can use as the this pointer:

(box->*h)(xPos, yPos, width, height);
Copy after login

Example 2: Adding Member Functions to a List

Consider the code snippet:

std::list<HitTest> list;

for (std::list<Box*>::const_iterator i = boxList.begin(); i != boxList.end(); ++i)
{
    Box * box = *i;
    list.push_back(&box->HitTest);
}
Copy after login

Here, you are adding member functions of the Box class to the list list. Note that you are taking the address of the member function using &box->HitTest.

The above is the detailed content of How Do I Call a Pointer to a Member Function in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template