C++指向类的方法的指针与命令模式

#include <iostream>
#include <typeinfo>
using namespace std;

void sar(){}
static void rar(){}

class Foo
{
public:
	typedef void (Foo::*ACTION)();  // Foo空间内指向Foo成员的函数指针类型,可以指foo
    typedef void (*AC2)();          // Foo空间内指向全局函数的指针类型,可以指sar
	void foo()
	{
		cout << "foo is called" << endl;
	}

	static void bar(){}
};

//
// Command类,保存一个Foo对象和对象的一个方法,
// 执行过程就是通过对象调用方法,达到命令封装的效果。
//
class Command
{
public:
	Command(Foo &f, Foo::ACTION act):f_(f), act_(act){}
	void execute()
	{
		(f_.*act_)();
	}

	Foo &f_;
	Foo::ACTION act_;
};

int main()
{
	typedef void (*PF)();
	Foo f;
	Command c(f, &Foo::foo);
	c.execute();

	cout << typeid(&Foo::foo).name() << endl;       // void (__thiscall Foo::*)(void)
	cout << typeid(Foo::bar).name() << endl;        // void __cdecl(void)
	cout << typeid(sar).name() << endl;             // void __cdecl(void)
	cout << typeid(rar).name() << endl;             // void __cdecl(void)
    cout << typeid((Foo::AC2)NULL).name() << endl;  // void (__cdecl*)(void),类型跟Foo没关系!

    PF p = &Foo::foo;           // error,类型不匹配
	Foo::ACTION p = &Foo::foo;  // ok
	(*p)();     // error,不能调用
    (f.*p)();   // ok
	return 0;
}

// 可以把Command类做成模板

template<typename CLASS, typename METHORD>
class Command
{
public:
	Command(CLASS &c, METHORD m):c_(c), m_(m){}
	void execute()
	{
		(c_.*m_)();
	}

	CLASS &c_;
	METHORD m_;
};

Command<Foo, Foo::ACTION> c(f, &Foo::foo);



这是神马狗B论坛。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值