如何通过范围解析操作员在使用指针到成员时获取类成员的地址? [英] How Does Getting the Address of a Class Member Through a Scope Resolution Operator Work When Using a Pointer-to-Member?
问题描述
使用指向成员的指针(AKA点星形或箭头星形)访问类成员时,可以使用以下语法:
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';
我的问题是& A :: n
语句工作?
在上面的例子中, n
是一个变量。如果不是成员变量, n
是一个函数(我们定义了一个指向成员函数而不是指向成员的指针)我可能会认为,由于类的函数可以有效地静态(参见Nemo的注释),我们可以通过& A :: some_function
找到一个类的函数地址。但是如何通过类范围解析来获得非静态类成员的地址?当我打印& A :: n
的值时,这更令人困惑,因为输出只是 1
。
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
这篇关于如何通过范围解析操作员在使用指针到成员时获取类成员的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!