- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- template<typename T>
- class A
- {
- private:
- typedef int (T::*delegateFun)(int); // 将T类中的函数设置未typedef
- typedef int (T::*unknowFun)(int,int);
- T *_This; // T类对象
- delegateFun _deleGate; // T类对象的函数
- unknowFun _unknowFun;
- public:
- // This被代理的对象,delegateFun被代理的方法
- // A(T *This, int (T::*delegateFun)(int))
- // {
- // _This = This;
- // _deleGate = delegateFun;
- // }
- A(T *This, delegateFun pFun)
- {
- _This = This;
- _deleGate = pFun;
- }
- A(T *This, unknowFun pFun)
- {
- _This = This;
- _unknowFun = pFun;
- }
- // 被代理的函数
- int execue(int c)
- {
- return (_This->*_deleGate)(c);
- }
- int execue2(int i,int j){
- return (_This->*_unknowFun)(i,j);
- }
- };
- class B
- {
- public:
- int FunA(int a)
- {
- return a + 10;
- }
- int FunB(int a)
- {
- return a - 10;
- }
- // 模板函数
- template <class Type>
- Type Func(Type t1,Type t2){
- return t1 + t2;
- }
- };
- int main(int argc, char* argv[])
- {
- B *objB = new B();
- cout << objB->Func(3.14,2.2) << endl;
- cout << "---------" << endl;
- A<B> delegateObj1(objB, (&B::FunA));
- A<B> delegateObj2(objB, (&B::FunB));
- cout<<delegateObj1.execue(10)<<endl;
- cout<<delegateObj2.execue(20)<<endl;
- cout << "---------" << endl;
- A<B> delegateObj3(objB, (&B::Func));
- cout<< delegateObj3.execue2(9,8) << endl;
- cout << "Over~" << endl;
- return 0;
- }
5.34
---------
20
10
---------
17
Over~
请按任意键继续. . .