[英]why can get address of member function by class type
I met this code: 我遇到了以下代码:
auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);
in the previous code, we can apply the address operator to a member function while there is no instance object been created, how can that be possible? 在前面的代码中,我们可以在没有创建实例对象的情况下将address运算符应用于成员函数,那怎么可能呢?
The type system of C++ contains a lesser-known category of types which are pointers to members . C ++的类型系统包含一个鲜为人知的类型类别,它们是指向member的指针 。 Given any class type
C
and any object or function type T
, there is a pointer-to-member type TC::*
. 给定任何类类型
C
和任何对象或函数类型T
,就存在一个指向成员的指针类型TC::*
。 Values of these types can be obtained by applying the address-of operator to the qualified name of a class member. 这些类型的值可以通过将address-of运算符应用于类成员的合格名称来获得。 For example:
例如:
struct Foo;
int Foo::* pi; // C = Foo, T = int
void (Foo::* pf)(bool, int); // C = Foo, T = void(bool, int)
struct Foo {
int a;
int b;
void f(bool, int);
void g(bool, int);
};
pi = &Foo::a;
pf = &Foo::f;
The member pointer itself only selects a class member abstractly, unrelated to any class instance . 成员指针本身仅抽象选择一个类成员,与任何类实例无关。 To actually use the pointer, you need a class instance, and the member-dereference operator
.*
: 要实际使用指针,您需要一个类实例和member-dereference运算符
.*
:
Foo x;
int n = x.*pi; // gets x.a
(x.*pf)(true, n); // calls x.f(true, n)
pf = &Foo::g;
(x.*pf)(true, n); // calls x.g(true, n)
(The parentheses in the call expression through the pointer-to-member pf
are necessary because otherwise the expression a.*b(c)
means a.*(b(c))
. This is occasionally a point of confusion for new users.) (通过指向成员的指针
pf
的调用表达式中的括号是必需的,因为否则表达式a.*b(c)
意味着a.*(b(c))
。这对于新用户而言有时是一个困惑点。 )
Don't confuse a pointer-to-member to an object member with a pointer to the actual object! 不要将指向对象成员的指针与指向实际对象的指针混淆!
int * p = &(x.*pi); // p = &x.a
Here p
points to the actual int
subobject xa
and is an ordinary object pointer, whereas pi
is a pointer-to-member that abstractly selects the Foo::a
member of a Foo
object. 这里
p
指向实际的int
子对象xa
并且是一个普通的对象指针,而pi
是一个指向成员的指针,该成员抽象地选择了Foo::a
Foo
对象Foo::a
成员。
Taking the address of Foo
's member function gives you a pointer to member function. 使用
Foo
成员函数的地址可以为您提供一个指向成员函数的指针。 This type is completely independent of any Foo
object. 此类型完全独立于任何
Foo
对象。 If you're going to actually call the function, you need to provide a Foo
object. 如果要实际调用该函数,则需要提供一个
Foo
对象。 In this case, the this
parameter of Foo::print_sum
is being bound to &foo
with std::bind
. 在这种情况下,
Foo::print_sum
的this
参数通过std::bind
绑定到&foo
。
当然,您需要具有名为foo
Foo
类型的实例,因为成员函数Foo::print_sum
绑定到foo
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.