Chapter09 function improvement

1. Function default parameters.
If we pass in the data ourselves, use our own data. If not, then use the default value.
Syntax: return value type function name (formal parameter = default value)
Note:
1) If a certain location already exists Default parameters, then from this position onwards, from left to right, there must be default values.

int func(int a, int b = 20,int c = 30)
{
	return a + b + c;
}

2) If the function declaration has default parameters, the function implementation cannot have default parameters
PS: The initial default value can only be assigned once when the function is declared and defined.

int func2(int a, int b);
int func2(int a = 10, int b = 20)
{
	return a + b;
}

2. Function placeholder parameters
Function: The formal parameter list of a function in C++ can have placeholder parameters, which are used as placeholders. This position must be filled when calling the function.
Syntax: return value type function name (data type) { }

void func3(int a, int)
{
	cout << a << endl;
}

3. Function overloading
: Function names can be the same to improve reusability

The conditions for function overloading are:
1) In the same scope
2) The function name is the same
3) The function parameter types are different or the number is different or the order is different

Note: The return value of a function cannot be used as a condition for function overloading

void func4()
{
	cout << "基础函数" << endl;
}

void func4(int a)
{
	cout << "个数不同的调用" << endl;
}

void func4(double a)
{
	cout << "类型不同的调用" << endl;
}

void func4(int a,double b)
{
	cout << "个数不同的调用" << endl;
}

void func4(double a, int b)
{
	cout << "顺序不同的调用" << endl;
}

Notes on function overloading:
1) Reference as an overloaded function

void func5(int &a)
{
	cout << "void func5(int &a)调用" << endl;
}

void func5(const int& a)
{
	cout << "void func5(const int& a)调用" << endl;
}

Both are of different types

void func5Test()
{
	int a = 10;
	func(a);
	//输出的结果是:void func5(int &a)调用

	func(10);
	//输出的结果是:void func5(const int &a)调用
}

2) Function overloading encounters function default parameters

void func5(int a)
{
	cout << "void func5(int &a)调用" << endl;
}

void func5(int a,int b = 10)
{
	cout << "void func5(const int& a)调用" << endl;
}

PS: If I call the function: func5(10) at this time;
the function overload encounters the default parameters, and there is ambiguity, an error will occur.

Guess you like

Origin blog.csdn.net/qq_43036676/article/details/100738915