C++ function pointer variable call function
In C++, a pointer variable can also point to a function. A function is assigned to an entry address at compile time. This function entry address is called a pointer to the function. You can use a pointer variable to point to the function, and then call this through the pointer variable function.
The general definition of a pointer variable to a function is
函数类型 (*指针变量名)(函数形参表);
Classic case: C++ finds the largest number of two numbers.
#include<iostream>//预处理
#include<string>
using namespace std;//命名空间
int main()//主函数
{
int max_Number(int num1,int num2);//函数声明
int num1,num2,max;//定义变量
cin>>num1>>num2;//键盘输入两个数
max=max_Number(num1,num2);//调用max_Number
cout<<"大数是:"<<max<<endl;//输出结果
return 0; //函数返回值为0;
}
int max_Number(int num1,int num2)//自定义求最大值函数
{
int temp;//定义中间变量
if(num1>num2)//如果num1大于num2
{
temp=num1;//把大的赋值给temp
}
else
{
temp=num2;//把大的赋值给temp
}
return temp;//把temp值返回到函数调用处
}
After executing this program, it will output:
5 9
大数是:9
--------------------------------
Process exited after 7.108 seconds with return value 0
请按任意键继续. . .
You can use a pointer variable to point to the max_Number function, and then call this function through the pointer variable. The method of defining a pointer variable to the max_Number function is:
int (*p)(int,int);
C++ function to find the largest number of two numbers.
More cases can go to the public account: C language entry to proficient