Function call operator overload

Source: Internet
Author: User

If the class is overloaded with the function call operator, we can use the class object like using the function. Because such classes can also store states, they are more flexible than common functions.

For example:

Struct absint {int operator () (INT Val) const {return Val <0? -Val: Val ;}}

This class only defines one operation: the function call operator, which accepts an int type real parameter and returns the absolute value of the real parameter.

We use the call operator to make an absint object act on a real parameter list. This process looks like a function call process:

Int I =-42; absint absobj; int UI = absobj (I); // pass I to absobj. Operator ()

Even if absobj is just an object rather than a function, we can "call" this object. The call object is actually running the overloaded call operator. In this example, the operator accepts an int value and returns its absolute value.

Note: The function call operator must be a member function. A class can define multiple call operators of different versions, which are different in the number or type of parameters. (Heavy Load)

If a class defines the call operator, the class object is called a function object. Because we can call such an object, all of them say that these objects are "behave like functions ".

 

Function object class with status

Like other classes, function object classes can contain other members besides operator. Function object classes usually contain some data members who are used to customize the operations in call operators.

 

Function call operator overload

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.