C++ Beginner - Function Overloading

Preface: In addition to using functions with the same name in different namespaces in C++, there is another way to support functions with the same name in the same scope—function overloading.

1. What is function overloading?

C++ allows several functions of the same name with similar functions to be declared in the same scope, which is often used to deal with the problem of different data types that implement similar functions.

2. Three rules for function overloading

1. Different types'
2. Different types order
3. Different amounts of formal parameters.
Attention! ! ! :
1. Different return value types do not constitute function overloading
2. Formal parameters are named according to your preference, so different formal parameters do not constitute function overloading.

Example:

//一
double  Func(int x, double y)
{
    
    
	cout << x+y << endl;
}
//二
double Func(int x, double y, int z)
{
    
    
	cout << x + y + z << endl;
}
//三
double Func(double x, int y)
{
    
    
	cout << x + y << endl;
}

//返回值类型跟三不同,不能构成函数重载。
//int Func(double x, int y)
//{
    
    
//	cout << x + y << endl;
//}

int main()
{
    
    
	Func(1, 2.2);     //一
	Func(1, 1.1, 2); //二
	Func(1.1, 2);     //三
	return 0;
}

The console output is as follows:

Insert image description here

3. Special circumstances

I would like to describe the special situations I have encountered:
We have learned the default parameters before, so can the following situations be run?

void  Func(int x, int y)
{
    
    
	cout << x+y << endl;
}
void Func(int x, int y, int z = 10)
{
    
    
	cout << x + y + z << endl;
}
int main()
{
    
    
	Func(1, 2); 
	return 0;
}

The Func() here can be either the first or the second, so there is ambiguity and the compiler will report an error.
Insert image description here

BB at the end of the article: For friends who have any questions, feel free to leave a message in the comment area. If there are any questions, friends are welcome to point out in the comment area. The blogger will confirm the modification as soon as possible after seeing it. Finally, it is not easy to make. If it is helpful to my friends, I hope it will make you rich and give me some likes and attention.
Insert image description here

Guess you like

Origin blog.csdn.net/qq_73390155/article/details/132175369