"C++ Primer" reading notes-Chapter 06 function matching

Author: Ma Zhifeng
link: https: //zhuanlan.zhihu.com/p/23899851
Source: know almost
copyrighted by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

statement:

  • The content in the article is collected and compiled from "C++ Primer Chinese Edition (5th Edition)", and the copyright belongs to the original book.
  • The original book has more detailed and wonderful interpretations, please buy genuine books for learning.
  • This article is only for learning and communication, any form of reprinting is prohibited

When there are multiple overloaded functions, which one will be called?

void f();
void f(int);
void f(int, int);
void f(double, double=3.14);
f( 5.6 );

Function matching process

  1. Find all functions with the same name visible at the call site as candidate functions
  2. Find the same number of parameters, and actually participate in the same or convertible function of the formal parameter, called a feasible function
  3. Find the best match

For the above example

  1. 4 functions are candidate functions
  2. The first and third parameters are different in number and are excluded, the second and fourth are feasible functions
  3. The closer the actual parameter types are, the better they match, so here f(5.6) calls the fourth function

The case of multiple formal parameters

The following conditions must be met at the same time

  1. The matching of each argument is not inferior to the matching of other feasible functions
  2. The matching of at least one argument is better than the matching of other feasible functions,
    and there can only be one function that meets the condition

For example, f( 42, 5.6);, f(int, int) wins when considering the first parameter, f(double, double) wins when considering the second parameter, so there is no best match, the call is wrong

Argument type conversion

As mentioned earlier, the closer the types of actual and formal parameters are, the better the match. There are the following sorting rules:

  1. Exact match
    • The actual and formal parameters are of the same type
    • The actual parameter is converted from the array or function type to the corresponding pointer
    • Add top-level const to actual parameters or remove top-level const from actual parameters
  2. Matching through const conversion
  3. Matching through type promotion
  4. Matching achieved through arithmetic type conversion or pointer conversion
  5. Matching through class type conversion

In short, we should be careful about overloaded functions in our programs to avoid calling errors

Guess you like

Origin blog.csdn.net/qq_26751117/article/details/53319018