posts - 14,  comments - 51,  trackbacks - 0
在分析ACE的原码时发现有一种平时比较少见的调用方式,记得以前有人用C++描述Command时也用了这种方式,不过他们的代码都包装为模板,不方便理解.这里,我不用模板简单的展示其特点:
#include <iostream>
using namespace std;
 
class CA
{
public:
    CA()
    {
        cc 
= 1;
    };
    
    
int func1(int a, int x)
    {
        cout
<<"func1"<<endl;
        
        cc 
= a + x;
        cout
<<"cc is :"<< cc <<endl;
        
return cc;
    }
    
int func2(int a, int y)
    {
        cout
<<"func2"<<endl;
        cc 
= cc + a * y;
        cout
<<"cc is:"<<cc<<endl;
        
return cc;
    }

    typedef 
int (CA::*FUNC)(int a, int y);

    
int Test1() 
    {
        FUNC f;
        f 
= &CA::func2;

        
return (this->*f) (1020);         
    }
    
    
int test2(FUNC func,int a, int b)
    {
        //ACE中是先做一些共同的复杂的事,然后调用不同的func部分:
        
return (this->*func)(a,b);
    }
private:
    
int cc;
};
 
int main( void )
{
    CA a;
    a.Test1();
    a.test2(
&CA::func2,11,3); 
    
return 0;
}

很酷!调用者可以把类的函数作为参数传递.
好再开下面,利用继承的关系,我们还可以做到同样效果:
#include <iostream>
using namespace std;
class CB
{
public:
    
virtual int func1(int a, int x)=0;
    
virtual int func2(int a, int x)=0;
    typedef 
int (CB::*FUNC)(int a, int y);

    
int Test1() 
    {
        FUNC f;
        f 
= &CB::func2;
        
return (this->*f) (1020);         
    }
    
    
int test2(FUNC func,int a, int b)
    {
        
return (this->*func)(a,b);
    }
};    

class CA:public CB
{
public:
    CA()
    {
        cc 
= 1;
    };
    
    
int func1(int a, int x)
    {
        cout
<<"func1"<<endl;
        
        cc 
= a + x;
        cout
<<"cc is :"<< cc <<endl;
        
return cc;
    }
    
int func2(int a, int y)
    {
        cout
<<"func2"<<endl;
        cc 
= cc + a * y;
        cout
<<"cc is:"<<cc<<endl;
        
return cc;
    }

    
private:
    
int cc;
};
 
int main( void )
{
    CB 
*pB = new CA();     
    pB
->Test1();
    pB
->test2(&CB::func2,11,3); 
    delete pB;
    
return 0;
}
上面的例子如果应用到Command模式中,func1 和func2就可以分别是Execute 跟 UnDo的接口了.至于如何实现,就是派生类的问题了.
(上述代码均在MinGW中测试通过)
 

posted on 2009-02-25 17:32 名羽 阅读(1664) 评论(3)  编辑 收藏 引用 所属分类: c++& vc

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理