Home >Backend Development >C++ >How Do C \'s `->*` and `.*` Pointer-to-Member Operators Work?
*` and `.*` Pointer-to-Member Operators Work? " />
Understanding Pointer-to-Member Operators -> and . in C
Despite existing documentation, grasping the meaning of pointer-to-member operators -> and . in C can be elusive. This article aims to clarify their functionality and their application in various scenarios.
What are -> and .?
Pointer-to-member operators are used to access member functions indirectly through pointers or references to objects. -> dereferences a member function pointer to call a member function of the referenced object. . dereferences a member pointer to call a member function of the pointed object.
When to Use -> and .?
X* px = new X; pointer somePointer = &X::f; (px->*somePointer)(); // Calls px->f()
X& rx = x; pointer somePointer = &X::f; (rx.*somePointer)(); // Calls rx.f()
Example
Consider the following code:
struct X { void f() {} void g() {} }; int main() { X x; void (X::*pointer)() = &X::f; // Call x.f() using .* (x.*pointer)(); X* px = new X; // Call px->f() using ->* (px->*pointer)(); return 0; }
In this example, pointer dereferences the member function pointer &X::f and assigns it to pointer. Then, . is used on x to call x.f(), and -> is used on px to call px->f().
By understanding the difference between -> and . and when each one is appropriate, developers can effectively handle member function pointers and indirect function calls in C .
The above is the detailed content of How Do C \'s `->*` and `.*` Pointer-to-Member Operators Work?. For more information, please follow other related articles on the PHP Chinese website!