Using C ++ overload to implement functions similar to "class member pointer"

Source: Internet
Author: User

 

The Code is as follows:

 

//: PointerToMemberOperator. cpp

# Include <iostream>

Using namespace std;

 

Class Dog

{

Public:

Int run (int I) const

{

Cout <"run \ n ";

Return I;

}

Int eat (int I) const

{

Cout <"eat \ n ";

Return I;

}

Int sleep (int I) const

{

Cout <"ZZZ \ n ";

Return I;

}

Typedef int (Dog: * PMF) (int) const;

// Operator-> * must return an object

// That has an operator ():

Class FunctionObject

{

Dog * ptr;

PMF pmem;

Public:

// Save the object pointer and member pointer

FunctionObject (Dog * wp, PMF pmf)

: Ptr (wp), pmem (pmf)

{

Cout <"FunctionObject constructor \ n ";

}

// Make the call using the object pointer

// And member pointer

Int operator () (int I) const

{

Cout <"FunctionObject: operator () \ n ";

Return (ptr-> * pmem) (I); // Make the call

}

};

FunctionObject operator-> * (PMF pmf)

{

Cout <"operator-> *" <endl;

Return FunctionObject (this, pmf );

}

};

 

Int main (){

Dog w;

Dog: PMF pmf = & Dog: run;

Cout <(w-> * pmf) (1) <endl;

Pmf = & Dog: sleep;

Cout <(w-> * pmf) (2) <endl;

Pmf = & Dog: eat;

Cout <(w-> * pmf) (3) <endl;

}

 

 

From yucan1001

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.