简体   繁体   中英

How Does Getting the Address of a Class Member Through a Scope Resolution Operator Work When Using a Pointer-to-Member?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM