How to get the address of a class member using the permission permission operator when working with the member pointer?

When using a pointer-to-member (AKA point-to-point or star-arrow) 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 the &A::n operator works?

In the above example, n is a variable. If instead of a member variable, n was a function (and we specified a member-pointer-function instead of a member-pointer), I can assume that since the functions of the class can be static (see the Nemo comment), we could find the address of a class function via &A::some_function . But how can we get the address of a non-static member of a class through class resolution? This is even more confusing when I print the value &A::n , because the output is just 1 .

+3
c ++ scope pointers class pointer-to-member
Jul 19 '13 at 21:46
source share
1 answer

When you declare a pointer to member data, it is not limited to any particular instance. If you want to know the address of the data member for this instance, you need to take the address of the result after execution .* Or ->* . For example:

 #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 
+2
Jul 19 '13 at 22:09
source share



All Articles