我刚刚看到了a post,在其中我发现了一些我以前从未见过的东西,简而言之,它是:
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
}怎么做呢?传入&A::_x,然后使用(*a_ptr).*m_ptr引用它
我想,&A::_x总是指同一个地址,但是不同的对象有不同的_x,怎么做呢?
发布于 2012-08-14 07:58:38
&A::_x是一个指向成员的指针,而不是指针.相反,把它看作是某种相对的构造,它告诉您在对象中找到特定成员元素的位置。只有与实例引用一起,才能找到由成员指针提供的实例的实际子对象。
比较:
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::yhttps://stackoverflow.com/questions/11947667
复制相似问题