C++函数使用的几种方式
函数是程序运行的一种功能模块,可以看成一个嵌入在主程序中的一个小程序,函数调用涉及栈切换等。为了变成更加方便,可以把函数看成一个变量,一个对象来使用。
1、基于模板function<函数签名>(函数名) 来实现函数调用。
2、基于函数指针实现函数调用 ,使用typedef得到函数指针类型。
3、类机制重载函数调用运算符,实现函数对象,可以在类里定义一些变量记录函数的运行状态。
代码实现如下:
#include<bits/stdc++.h>
using namespace std;
void display(int a, int b){
cout << a+b << endl;
}
//1、基于模板function<函数签名>(函数名) 来实现函数调用
void test1(){
auto f = function<void(int,int)>(display);
f(2,3);
}
//2、基于函数指针实现函数调用 ,使用typedef得到函数指针类型
void test2(){
typedef void(*func)(int,int);
func p = display;
p(6,3);
}
//3、类机制重载函数调用符,实现函数对象,可以在类里定义一些变量记录函数的运行状态。
class myfunc{
public:
void operator()(int a, int b){
cout << a + b << endl;
}
};
void test3(){
myfunc f;
f(2,6);
}
int main(){
test3();
return 0;
}