Note on function overloading
Question one
#include "iostream"
using namespace std;
void func(const int& a)
{
cout << "调用func(const int& a)函数" << endl;
}
void func(int& a)
{
cout << "调用func(int& a)函数" << endl;
}
int main()
{
int a = 10;
func(a);
}
Which overloaded function is called by func(a) in the above code?
The priority of calling a function depends on "the type of the passed parameter is closest to the parameter of the overloaded function".
Function overload status one:
void func(const int& a) // 该函数形参的a为“只读”状态
{
cout << "调用func(const int& a)函数" << endl;
}
Function overload status two:
void func(int& a) // 该函数形参的a为“可读可写”状态
{
cout << "调用func(int& a)函数" << endl;
}
In the main function, the parameter passed in to the func function is a of type int. At this time, the actual parameter a is "readable and writable state", so the "function overload state two" is called.
Question two
#include "iostream"
using namespace std;
void func(const int& a)
{
cout << "调用func(const int& a)函数" << endl;
}
void func(int& a)
{
cout << "调用func(int& a)函数" << endl;
}
int main()
{
int a = 10;
func(a);
}
Under what circumstances can the above program call "function overload status one"?
#include "iostream"
using namespace std;
void func(const int& a)
{
cout << "调用func(const int& a)函数" << endl;
}
void func(int& a)
{
cout << "调用func(int& a)函数" << endl;
}
int main()
{
func(10);
}
At this time, you can call "function overload state one", because the incoming formal parameter is "constant", which is consistent with "function overload state one incoming parameter-const constant". Looking back at the formal parameters of function overloading state 1, the formal parameters of function overloading state 1 are "variables containing "available memory space accessible". Obviously, the constant 10 does not meet the requirements.
Question three
#include "iostream"
using namespace std;
void func(const int& a)
{
cout << "调用func(const int& a)函数" << endl;
}
void func(int& a)
{
cout << "调用func(int& a)函数" << endl;
}
void func(int& a, int b = 10)
{
cout << "调用func(int& a, int b = 10)函数" << endl;
}
int main()
{
int a = 10;
func(a);
}
Can the above program run normally?
The answer is "NO".
When you pass in a non-const integer variable a, there are two func functions:
① void func(int& a, int b = 10)
② void func(int& a)
However, these two functions have no calling priority, so this program cannot run normally!