A study of C + + pointers (iv) function objects

Source: Internet
Author: User
Tags definition int size

The function object is not a function pointer. However, in program code, it is called like a function pointer, followed by parentheses.

This is the entry-level essay, which is about the definition of a function object, the use of it, and its relationship to function pointers, member function pointers.

Mu Feng Xiao Build

A function object is essentially a class that implements the operator ()-bracket operator.

For example:

class Add
{
public:
  int operator()(int a, int b)
  {
    return a + b;
  }
};

Add add; // 定义函数对象
cout << add(3,2); // 5

The function pointer version is:

int AddFunc(int a, int b)
{
  return a + b;
}
typedef int (*Add) (int a, int b);

 Add add = &AddFunc;
cout << add(3,2); // 5

Oh, in addition to the definition of the same way, the use of the same way. are:

cout << Add (3,2);

Since function objects and function pointers are not different in how they are used, why use a function object? Quite simply, a function object can carry additional data, and the pointer is not.

Here's an example of using additional data:

class less
{
public:
    less(int num):n(num){}
    bool operator()(int value)
    {
        return value < n;
    }
private:
    int n;
};

When in use:

Less isless (10);

cout << isless (9) << "" << isless (12);//Output 1 0

This example seems too trifling to change one:

const int SIZE = 5;
int array[SIZE] = { 50, 30, 9, 7, 20};
// 找到小于数组array中小于10的第一个数的位置
int * pa = std::find_if(array, array + SIZE, less(10)); // pa 指向 9 的位置
// 找到小于数组array中小于40的第一个数的位置
int * pb = std::find_if(array, array + SIZE, less(40)); // pb 指向 30 的位置

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.