How do I declare and use a pointer to a class member function?

Source: Internet
Author: User

How do I declare and use a pointer to a class member function? (Top)

The syntax is similar to a regular function pointer, but you also have to specify the class name. Use the. * And-> * operators to call the function pointed to by the pointer.
Collapse

Class cmyclass
{
Public:
Int addone (unsigned N) {return n + 1 ;}
Int addtwo (unsigned N) {return n + 2 ;}
};
Main ()
{
Cmyclass myclass, * pmyclass = & myclass;
INT (cmyclass: * pmethod1) (unsigned); // full declaration syntax
Pmethod1 = cmyclass: addone; // sets pmethod1 to the address of addone
Cout <(myclass. * pmethod1) (100); // callmyclass. addone (100 );
Cout <(pmyclass-> * pmethod1) (200); // callpmyclass-> addone (200 );
Pmethod1 = cmyclass: addtwo; // sets pmethod1 to the address of addtwo
Cout <(myclass. * pmethod1) (300); // callmyclass. addtwo (300 );
Cout <(pmyclass-> * pmethod1) (400); // callpmyclass-> addtwo (400 );

// Typedef a name for the function pointer type.
Typedef int (cmyclass: * cmyclass_fn_ptr) (unsigned );
Cmyclass_fn_ptr pmethod2;
// Use pmethod2 just like pmethod1 abve ....
}

The line collapse
INT (cmyclass: * pmethod1) (unsigned );
Pmethod1 is a pointer to a function in cmyclass; that function takes an unsigned parameter and returns an int.

Note that cmyclass: addone is very different from cmyclass: addone (). The first is the address of the addone method in cmyclass, while the second actually callthe method.

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.