C++ third bullet: function overloading

concept

Function overloading is a special case of functions. In C++, several functions of the same name with similar functions are allowed to be declared in the same scope. The formal parameter lists (number or types or order of parameters) of these functions with the same name must be different. Function overloading is often used to deal with the problem of different data types with similar functions. For example, in the problem of adding two numbers in our mathematics, we can add two integer numbers, or add double numbers, and so on.
example:

#include <iostream>
using namespace std;

int Add(int left, int right)
{
    
    
	return left + right;
}
double Add(double left, double right)
{
    
    
	return left + right;
}
long Add(long left, long right)
{
    
    
	return left + right;
}
int main()
{
    
    
	Add(10, 20);
	Add(12.12, 12.13);
	Add(12L, 30L);
	return 0;
}

Note: In C++, if only the return value type is different, it cannot constitute an overload, such as the following example

short Add(short left, short right)
{
    
    
	return left + right;
}
int Add(short left, short right)
{
    
    
	return left + right;
}
//不构成重载

Why can't these two functions constitute an overloaded function? This is because in C++, the return value can be ignored when calling a function. If we use these two functions, the compiler will not know which function we are calling.
From this, we can summarize the rules of C++ function overloading

1.函数名称必须相同。
2.参数列表必须不同(个数不同、类型不同、参数排列顺序不同等)。
3.函数的返回类型可以相同也可以不相同。
4.仅仅返回类型不同不足以成为函数的重载

Why does C++ support function overloading, but C language does not support it

Insert picture description here
Insert picture description here
It can be seen from these two figures that when the compiler compiles .c and .cpp, the renaming of the function is different. When compiling the .c file, it just adds "_" in front of the function name, that is, If the names of the two functions are Add(); although the parameters inside are not the same, they will be renamed to "_Add" when the compiler compiles, because the compiler does not know what we want to call That function will make an error; but in C++, the name of the function is renamed to "?Add@@YANNN@Z" in the form of "?Add@@YANNN@Z" in C++, where'? 'Indicates the beginning of the name,'? 'Following is the function name "@@YA" which indicates the beginning of the parameter list, and the following 3 characters respectively indicate the return value type and the two parameter types. "@Z" means the end of the name, which ensures that the names in the symbol tables generated by the two functions are different, and there will be no errors during compilation, so C++ supports function overloading.

Guess you like

Origin blog.csdn.net/qq_43825377/article/details/109234523