member function pointers for the c++--class and Mem_fun adapters

Source: Internet
Author: User

There is such a class that we base on this class:

1 classFoo2 {3  Public:4 5     //void (Foo::*) (int)6     voidFoointa)7     {8cout << a <<Endl;9     }Ten  One     //Void (*) (int) A     Static voidBarinta) -     { -cout << a <<Endl; the     } -};

We try to invoke the function pointer:

void (*pfunc) (int) = &Foo::foo;

Get compile Error:

Error:cannot convert 'void (Foo::*) (int) ' to 'void (*) (int in Initialization

The reason is simple, the class member function, which contains an implicit parameter, this, so the function void foo (int a) contains two parameters.
We should use the Void (Foo::*) (int) type to generate a function pointer using the following method:

void (Foo::* pFunc2) (int) = &Foo::foo; Foo F; (f. *PFUNC2) (*p = &F; (P->*pfunc2);

As opposed to the static member function, we can use it just like a normal function pointer, because the static member function does not have an implicit parameter of this.

We can call the function pointer by doing this:

void (*PFUNC3) (int) = &foo::bar;pfunc3 (N);

in function foo (), it contains an implicit parameter this, so how do we convert it?

We can do this by using Mem_fun in the STL, which is a function adapter.

The calling method is as follows:

Foo F; (Mem_fun);

The way the Mem_fun is transformed is this:

void (Foo::*) (int)  ,   voidint);

member function pointers for the c++--class and Mem_fun adapters

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.