[英]class::data_member vs class_object.data_member
I just saw a post in which I found something I never saw before, in short here it is: 我刚刚看到一个帖子,在其中找到了我从未见过的东西,简而言之,它是:
class A {
public:
int _x;
};
void foo(A *a_ptr, int *m_ptr)
{
cout << (*a_ptr).*m_ptr << endl; // here
}
int main()
{
A a;
a._x = 10;
foo(&a, &A::_x); // and here
}
How could it be done? 怎么做? Pass in
&A::_x
, and later refer it using (*a_ptr).*m_ptr
? (*a_ptr).*m_ptr
&A::_x
,然后使用(*a_ptr).*m_ptr
引用它(*a_ptr).*m_ptr
I thought, &A::_x
will always refer to the same address, but different objects have different _x
, how could it be done? 我以为
&A::_x
总是引用相同的地址,但是不同的对象具有不同的_x
,怎么办?
&A::_x
is a pointer-to-member, which is not a pointer. &A::_x
是指向成员的指针,而不是指针。 Rather, think of it as some relative sort of construct which tells you where inside an object you find a particular member element. 相反,可以将其视为某种相对的构造,它告诉您在对象内何处可以找到特定的成员元素。 Only together with an instance reference can you locate the actual subobject of that instance which is given by the member pointer.
只有与实例引用一起 ,您才能找到由成员指针指定的该实例的实际子对象。
Compare: 相比:
struct Foo { int x; int y; };
Foo a = { 1, 2 };
Foo b = { 3, 4 };
Foo c = { 5, 6 };
int * p = &a.x; // ordinary pointer-to-int
int Foo::*pm = &Foo::x; // pointer-to-member
int result = a.*pm + b.*pm + c.*pm; // aggregate Foo::x
// point to a different member:
pm = &Foo::y;
result = a.*pm + b.*pm + c.*pm; // aggregate Foo::y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.