When using a pointer-to-member (AKA dot-star or arrow-star) to access a class member, we can use the following syntax:
A * pa;
int A::*ptm2 = &A::n;
std::cout << "pa->*ptm: " << pa->*ptm << '\n';
My question is how does the &A::n
statement work?
In the above example n
is a variable. If instead of a member variable, n
was a function (and we defined a pointer-to-a-member-function instead of a pointer-to-a-member), I might reason that since a class's functions can be effectively static (see Nemo's comment), we could find a class's function's address via &A::some_function
. But how can we get the address of a non-static class member through a class scope resolution? This is even more confusing when I print the value of &A::n
because the output is merely 1
.
When you declare a pointer to member data, it isn't bounded to any particular instance. If you want to know the address of a data member for a given instance you need to take the address of the result after doing .*
or ->*
. For instance:
#include <stdio.h>
struct A
{
int n;
};
int main()
{
A a = {42};
A aa = {55};
int A::*ptm = &A::n;
printf("a.*ptm: %p\n", (void *)&(a.*ptm));
printf("aa.*ptm: %p\n", (void *)&(aa.*ptm));
}
prints as one possible output:
a.*ptm: 0xbfbe268c
aa.*ptm: 0xbfbe2688
来源:https://stackoverflow.com/questions/17756025/how-does-getting-the-address-of-a-class-member-through-a-scope-resolution-operat