全局函数指针数组typedef和成员函数指针数组类内外部typedef


#include <iostream>
#include <vector>

// 1.对全局函数指针数组typedef
typedef void(*FuncType01)();
typedef FuncType01 Func01Array[2];

void foo() 
{
	std::cout << "void foo()" << std::endl;
}

void bar()
{
	std::cout << "void bar()" << std::endl;
}

class A 
{
public:
	// 2.在类中对成员函数指针数组typedef
	typedef void (A::*FuncType02)() const;
	typedef FuncType02 Func02Array[2];

	void foo() const { std::cout << "void foo() const" << std::endl; }
	void bar() const { std::cout << "void bar() const" << std::endl; }
	void test() const
	{
		// 调用2的,类内部类型前不需要加类的域
		FuncType02 f = &A::foo;// 取成员函数地址必须加&,无论是否在类的内部还是外部
		Func02Array fs = {&A::foo, &A::bar};
		(this->*f)();
		for (int i = 0; i < 2; i++)
		{
			(this->*fs[i])();
		}
	}
};

// 3.在类外对成员函数指针数组typedef
typedef void (A::*FuncType03)() const;
typedef FuncType03 Func03Array[2];

int main()
{
	// 调用1的
	FuncType01 f1 = ::foo;//&可以不加
	Func01Array fs1 = { &foo, &bar };
	(*f1)();
	for (int i = 0; i < 2; i++)
	{
		(*fs1[i])();
	}

	// 调用2的
	A::FuncType02 f2 = &A::foo;// 取成员函数地址必须加&
	A::Func02Array fs2 = {&A::foo, &A::bar};
	A a;
	(a.*f2)();
	for (int i = 0; i < 2; i++)
	{	
		(a.*fs2[i])();
	}

	// 调用3的,不需要加类的域
	FuncType03 f3 = &A::foo;
	Func03Array fs3 = {&A::foo, &A::bar};
	A a2;
	(a2.*f3)();
	for (int i = 0; i < 2; i++)
	{	
		(a2.*fs3[i])();
	}

	a.test();

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值