【C++函数指针】

函数指针就是把一个函数赋值给变量的方法

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;
}

  • 43
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值