Jian Li provided the following class:
class C {
public:
void f() {}
int i;
};
John Carson wrote:
Non-static members can only be accessed via an object of the class, either
directly or indirectly (access indirectly via an object of the class occurs
when a non-static member is accessed within a non-static member function of
the same class). Thus you CANNOT access a member with C::f() or C::i inside
main().
Sometimes you may want to access the method C::f itself. First, here's
how you can do it explicitly, using a typedef for clarity:
typedef void (C::*CMethod)(void);
CMethod method = &C::f;
Now method is referring to the C::f method. To apply it to an instance
directly, use the .* or ->* operators:
C x;
(x.*method)();
This code invokes x.f().
Here's a practical example, in which clist is an STL container of C
instances (e.g., std::vector<C>, std::list<C>, etc.):
std::for_each(clist.begin(), clist.end(), std::mem_fun_ref(&C::f));
You can thus apply method f conveniently to every C instance in clist
without typing much.
The notation is similar for &C::i. You won't use it unless, say, you're
writing a templatized adapter for a family of C-language structures.
When the time comes, you'll think, "I wish I could just access an
arbitrary C field of a given type. Oh, wait, I can!"
-- Jonathan T. Higa, Ph.D. (hi****@comcast.net)