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

岁酱吖の 提交于 2019-12-06 00:30:21

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!