函数指针就是把一个函数赋值给变量的方法
void f(string name) {
cout << "f()->my name is :" << name << endl;
}
int main() {
f("1");
auto i = f;
i("2");
}
鼠标放在i上面可以看到类型,所以还可以这样:
void(*j)(string) = f;
j("2");
typedef void(*m)(string);
m a=f; a("4");
using n = void(*)(string);
n b=f; b("5");
//利用typeid查看类型->因为我们f函数是void类型,以及一个int参数
cout<<endl<<typeid(j).name()<<endl; //打印结果:void(_cdecl*)(int)
void(_cdecl*x)(int)=f; //这样也是可以的
接下来讲一下成员函数
#include<iostream>
#include<vector>
using namespace std;
class base {
public:
void show()
{
cout << "void show()" << endl;
}
void static f()
{
cout << "void static f()" << endl;
}
};
int main()
{
base bas;
auto j = bas.f; //OK
//auto i = bas.show; //err
auto i = &base::show;
(bas.*i)();
return 0;
}
看如下伪代码
void f(int value)
{
std::cout << "value:" << value << std::endl;
}
void function(const std::vector<int>V,void(*fun)(int))
{
for (int i : V)
fun(i);
}
main:
std::vector<int>V = { 1,2,3,4,5 };
function(V, f);
还可以更简单一点(涉及到lambda匿名函数)
#include<iostream>
#include<vector>
using namespace std;
void show( vector<int>nums, void(*f)( void(*)(int a),int x ),void (*k)(int) )
{
int x = 10;
for (auto i : nums)
{
f(k,x);
k(i);
}
}
int main()
{
vector<int>nums = { 2,3,4,5 };
//不用像普通函数一样要声明,在代码过程中实现,用完就丢。不算真正的函数
show(nums, [](void(*k)(int a),int x) { k(x); }, [](int value) {cout << "value:" << value << endl; });
return 0;
}