加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

指向C类方法的指针

发布时间:2020-12-16 10:38:03 所属栏目:百科 来源:网络整理
导读:在重构一些遗留的C代码时,我发现我可能通过某种方式定义一个可以指向共享相同签名的任何类方法的变量来删除一些代码重复.经过一番挖掘,我发现我可以做以下事情: class MyClass{protected: bool CaseMethod1( int abc,const std::string str ) { cout "case
在重构一些遗留的C代码时,我发现我可能通过某种方式定义一个可以指向共享相同签名的任何类方法的变量来删除一些代码重复.经过一番挖掘,我发现我可以做以下事情:

class MyClass
{
protected:
    bool CaseMethod1( int abc,const std::string& str )
    {
        cout << "case 1:" << str;
        return true;
    }

    bool CaseMethod2( int abc,const std::string& str )
    {
        cout << "case 2:" << str;
        return true;
    }

    bool CaseMethod3( int abc,const std::string& str )
    {
        cout << "case 3:" << str;
        return true;
    }

public:
    bool TestSwitch( int num )
    {   
        bool ( MyClass::*CaseMethod )( int,const std::string& );

        switch ( num )
        {
            case 1: CaseMethod = &MyClass::CaseMethod1;
                    break;
            case 2: CaseMethod = &MyClass::CaseMethod2;
                    break;
            case 3: CaseMethod = &MyClass::CaseMethod3;
                    break;
        }

        ...

        bool res = CaseMethod( 999,"hello world" );

        ...

        reurn res;
    }
};

我的问题是 – 这是正确的方法吗?我应该考虑Boost提供的任何东西吗?

编辑…

好吧,我的错误 – 我应该这样调用方法:

bool res = ( (*this).*CaseMethod )( 999,"Hello World" );

解决方法

你有一个指向成员的函数.它会解决你的问题.我很惊讶您的“TestSwitch”函数编译,因为调用语法与您可能期望的略有不同.它应该是:

bool res = (this->*CaseMethod)( 999,"hello world" );

但是,您可能会发现boost :: function和boost :: bind的组合使事情变得更容易,因为您可以避免奇怪的调用语法.

boost::function<bool(int,std::string)> f=
    boost::bind(&MyClass::CaseMethod1,this,_1,_2);

当然,这会将它绑定到当前的this指针:如果您愿意,可以使成员函数的this指针成为显式的第三个参数:

boost::function<bool(MyClass*,int,_2,_3);

另一种替代方法可能是使用虚函数和派生类,但这可能需要对代码进行重大更改.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读