Function overloading (7)

        Today we look at function overloading , so what is function overloading? Let's first look at the context in natural language, such as: word washing. It has different meanings in different scenes, such as: washing clothes, washing cars, washing faces, washing toilets, and brainwashing. The meaning of each word-washing collocation is different, which leads to the concept of overload.

        Overloading means that the same identifier has different meanings in different contexts . Overloading can be seen everywhere in natural language, so is there overloading in programming? C++ is an object-oriented language, of course, it supports function overloading. Function overloading in C++ is expressed as: a> define different functions with the same function name; b> the meaning of the function is different when the function name is matched with different parameters .

        Let's take the code as an example to analyze

#include <stdio.h>
#include <string.h>

int func(int a)
{
    return a;
}

int func(int a, int b)
{
    return a + b;
}

int func(const char* s)
{
    return strlen(s);
}

intmain()
{
    printf("%d\n", func(1));
    printf("%d\n", func(1, 2));
    printf("%d\n", func("hello"));
    
    return 0;
}

        We see that three functions are defined with the same function name, which is not acceptable in C language. Let's see if it is supported in C++?

picture.png

        We see that the compilation is passed and the function of the function is completed. So how can it be called function overloading? It must satisfy at least one of the following conditions: a> the number of parameters is different; b> the parameter types are different; c> the parameter order is different; can the following function be called function overloading?

int func(int a, const char* s)
{
    return a;
}

int func(const char* s, int a)
{
    return strlen(s);
}

        They are obviously function overloads because they satisfy the third condition above. What happens when a function default parameter encounters function overloading? Let's take a look at a sample code

#include <stdio.h>

int func(int a, int b, int c = 0)
{
    return a * b * c;
}

int func(int a, int b)
{
    return a + b;
}

intmain()
{
    printf("%d\n", func(1, 2));
    
    return 0;
}

        We see that two func functions are defined, the first and the last are default parameters. Can such a function be called function overloading? Does the compiler know exactly which function it should call? Let's look at the compilation results

picture.png

        We see the compile error, it says the function overload is ambiguous, it doesn't know which function to call. Although C++ adds a lot of features to C, obviously this is a bad feature, and these contradictory features are canceled in subsequent high-level languages ​​(such as Java, C#, etc.). So such function overloading is not advisable, so what are the guidelines for the compiler to call overloaded functions? A. Use all functions of the same name as candidates; B. Try to find feasible candidate functions: a> Exactly match the actual parameters. b> Can match actual parameters through default parameters. c> Match the actual parameters through the default type conversion; C. The matching fails: a> If the candidate function finally found is not unique, there will be ambiguity and the compilation will fail. b> Unable to match all candidates, the function is undefined, and the compilation fails ;

        Matters needing attention when overloading functions: a> The overloaded functions are essentially different functions independent of each other; b> The function types of the overloaded functions are different; c> The return value of the function is not tender as the basis for function overloading; the function Overloading is determined by the function name and parameter list! ! !

        Let's take a look at the essence of function overloading through a sample code

#include <stdio.h>

int add(int a, int b)    // int(int, int)
{
    return a + b;
}

int add(int a, int b, int c)    // int(int, int, int)
{
    return a + b + c;
}

intmain()
{
    printf("%p\n", (int(*)(int, int))add);
    printf("%p\n", (int(*)(int, int, int))add);
    
    return 0;
}

        We learned before that the function name is actually the entry address of the function, and we print its address through the type of the function. Let's take a look at the compilation results

picture.png

        We see that different addresses are printed, which means that the two overloaded functions are different. Let's compile it again in the C language compiler and see what the result is

picture.png

        We see that it reports an error saying that the add function is already defined. In C, as long as the function name is the same, it considers it to be the same function. Let's take a look at overloading and pointers, or take the code as an example for analysis

#include <stdio.h>
#include <string.h>

int func(int a)
{
    return a;
}

int func(int a, int b)
{
    return a + b;
}

int func(const char* s)
{
    return strlen(s);
}

typedef int(*PFUNC)(int a);

int main(int argc, char *argv[])
{
    int c = 0;

    PFUNC p = func;
        
    c = p(1);   
    
    printf("c = %d\n", c);
    
    return 0;
}

        We define a function pointer PFUNC on line 19, then we point it to the func function on line 25, will it know which function it is pointing to? Let's take a look at the compilation results

picture.png

        We see that the compilation passes, and it runs perfectly. Obviously it points to the first func function, because its type is int(int); so it matches the first func function.

        When a function overloading encounters a function pointer and assigns the overloaded function name to the function pointer: a> Select the candidate consistent with the function pointer parameter list according to the overloading rules; b> Strictly match the candidate's function type and the function pointer function type. Note: 1. Function overloading must occur in the same scope; 2. The compiler needs to use the parameter list or function type for function selection; 3. The entry address of the overloaded function cannot be obtained directly through the function name .

        In the actual project, the mutual call between C++ and C code is inevitable, and the C++ compiler can be compatible with the C language compilation method. But the C++ compiler will use the C++ compilation method first, and the extern keyword can force the C++ compiler to compile the C method . Let's take a look at a sample code


add.h source code

int add(int a, int b);


add.c source code

#include "add.h"

int add(int a, int b)
{
    return a + b;
}


test.cpp source code

#include <stdio.h>

extern "C"
{
#include "add.h"
}

int main(int argc, char *argv[])
{
    int c = add(1, 2);
    
    printf("c = %d\n", c);
    
    return 0;
}

        We first compile add.c into add.o file, and then compile test.cpp file to see if the result is as we thought

picture.png

        We see that the results have come to fruition. If we copy the code in test.cpp to test.c and compile it in C, can it pass?

picture.png

        We found that it doesn't recognize extern "C", so the question is, how do we ensure that a piece of C code will only be compiled in C? __cplusplus is a standard macro definition built into the C++ compiler. We can use this macro to ensure that the C code is compiled into an object file in a unified C way . Let's change the extern "C" code in the above test.cpp to the following, let's try it again

#ifdef __cplusplus
extern "C" {
#endif

#include "add.h"

#ifdef __cplusplus
}
#endif

        This is guaranteed to compile as C in a C++ compiler, and in a C compiler extern "C" has no effect. Let's compile and see the result

picture.png

        We see that it also compiles fine under the C compiler. There are two points to note in this section: A. The C++ compiler cannot compile overloaded functions in the C method; B. The compilation method determines the target name after the function name is compiled: a> The C++ compilation method compiles the function name and parameter list into target name. b> The C compilation method only compiles the function name as the target name.

        Through the study of function overloading, the summary is as follows: 1. Function overloading is a concept introduced in C++, and function overloading is used to simulate lexical collocations in natural languages; 2. Function overloading makes C++ have richer semantic expression capabilities , its essence is different functions that are independent of each other; 3. In C++, the function call is determined by the function name and function parameters; 4. Function overloading is an important upgrade of C++ to C; 5. Function overloading distinguishes different functions through the function parameter list The function of the same name; 6. The extern keyword can realize the mutual call of C and C++; 7. The compilation method determines the final target name of the function name in the symbol table.


        Welcome to learn C++ language together, you can add me QQ: 243343083 .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345320&siteId=291194637