A study of C + + pointers (ii) function pointers

Source: Internet
Author: User
Tags comparison sort

The data pointers are the most direct and commonly used in C/s + +, so it is easier to understand. function pointers, which act as run-time dynamic invocations (such as callback functions CallBack function), are common and useful tools.

Let's start with a simple function pointer. (This part is of little value, purely to elicit the next section)

2 General function pointers

void (*FP) ();

FP is a typical function pointer to a function that has no parameters and no return value.

void (*FP2) (int);

FP2 is also a function pointer that points to a function that has an integer parameter and no return value.

Of course, experienced people will generally recommend using a typedef to define the type of function pointers, such as:

typedef void (* FP) ();

FP FP3///the same definition as the FP above.

The main reason why a function pointer is so daunting for beginners is that it has too many parentheses; some uses of function pointers tend to make people stuck in the bracket heap out of the box, and here is not an example, because this is not the scope of this article, the TypeDef method can effectively reduce the number of parentheses, as well as the clear level, so be recommended. This article only considers a simple function pointer for the time being, so there is no need for a typedef.

If there are two functions:

void f1()
  {
      std::cout << "call f " << std::endl;
  }

  void f2(int a)
  {
      std::cout << "call f2( " << a << " )" << std::endl;
  }

Now we need to call it through the function pointer, we need to specify the function to the pointer:

fp = &f1; // 也可以用:fp = f1;
  fp2= &f2; // 也可以用:fp2= f2;
  void (*fp3)() = &f1; // 也可以用:void (*fp3)() = f1;
  //调用时如下:
  fp(); // 或 (*fp)();
  fp2(1); // 或 (*fp2)(1);
  fp3();  // 或 (*fp3)();

For both of these invocation methods, the effect is exactly the same, I recommend the previous one. The latter is more than just a dozen keyboards, but it also loses some flexibility. Don't say it here for a moment.

C + + emphasizes type safety. In other words, different types of variables can not be directly assigned to the value, or light warning, heavy error. This is a very useful feature that can often help us find the problem. Therefore, the insight that, C + + in any one of the outside warning can not be ignored. It was even suggested that no warning message should be present at compile time, that is, warnings should be treated as errors.

For example, if we assign F1 to FP2, the C + + compiler (vc7.1) will give an error:

FP2 = &f1;//Error C2440: "=": cannot be converted from void (__cdecl *) (void) to "void (__cdecl *) (int)"

FP1 = &f1;//OK

In this way, the compiler can help us find the coding errors, saving us the wrong time.

Consider the sort function of the C + + Standard Template Library:

// 快速排序函数
  template<typename RandomAccessIterator, typename BinaryPredicate>
     void sort(
        RandomAccessIterator _First, // 需排序数据的第一个元素位置
        RandomAccessIterator _Last,  // 需排序数据的最后一个元素位置(不参与排序)
        BinaryPredicate _Comp     // 排序使用的比较算法(可以是函数指针、函数对象等)
     );

For example, we have an array of integers:

int n[5] = {3,2,1,8,9};

To sort it in ascending order, we need to define a comparison function:

bool less(int a, int b)
  {
      return a < b;
  }

Then use:

Sort (n, n+5, less);

If you want to sort it in descending order, we just need to change the comparison function. The standard templates for C/C + + already provide the less and great functions, so we can compare them directly with the following statements:

Sort (n, n+5, great);

So, without changing the definition of the sort function, you can sort by any method, is it flexible?

This usage is very popular in the C + + Standard Template Library (STL). In addition, the callback (CallBack) function is often used in the operating system, in fact, the so-called callback function, the essence is the function pointer.

It looks very simple, it is the most common use of C language pointers. This is a wonderful thing, but when C + + comes, the world begins to change.

What if the comparison function used to sort is a member of a class?

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.