简体   繁体   English

如何通过范围解析操作员获取类成员的地址时使用指针到成员?

[英]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: 使用指向成员的指针(AKA点星或箭头星)访问类成员时,我们可以使用以下语法:

A * pa;
int A::*ptm2 = &A::n;
std::cout << "pa->*ptm: " << pa->*ptm << '\n';

My question is how does the &A::n statement work? 我的问题是&A::n语句是如何工作的?

In the above example n is a variable. 在上面的例子中, n是一个变量。 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 . 如果不是成员变量, n是一个函数(我们定义了指向成员函数的指针而不是指向成员的指针),我可能会因为一个类的函数可以有效地静态(看到Nemo的评论),我们可以通过&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 . 当我打印&A::n的值时,这更令人困惑,因为输出仅为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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