将成员函数分配给函数指针 [英] assign a member function to a function pointer

查看:86
本文介绍了将成员函数分配给函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个这样的班级:

If I have two classes like this :

class A
{
    public:
        int *(*fun)( const int &t );
        A( int *( *f )( const int &t ) ) : fun( f ) {}
};

class B
{
    private:
        float r;

        int *f(const int &t)
        {
            return new int( int( r ) + t );
        }
        A a;
        B() : a( A( f ) ) {}
};

这会导致编译器错误.

我想将f分配给a的功能指针.

I want to assign f to a's function pointer.

问题在于,A可以被许多类使用,而不仅仅是B,因此我不能简单地将fun定义为B::*fun.

The thing is that A can be used by many classes not just B so I can't simply define fun as B::*fun.

我在Internet上和stackoverflow上都没有找到解决使用函数指针的问题,这些函数指针与许多类都有各自的成员函数但具有相同的原型.

None of the posts I've found on the internet and here on stackoverflow address the issue of using the function pointers with many classes each having its own member function but the same prototype.

那该怎么办?

推荐答案

您的代码看起来令人困惑,而且我个人认为, C函数指针 C ++的OO实现上看起来很丑陋 >.因此,我建议您使用std::function.仅从C++11开始可用.如果您无法使用它,请尝试查看 Boost的实现

Your code looks confusing and, personally, I believe that C function pointers look ugly on C++'s OO implementation. So I would advise you to use the std::function. It only has been available since C++11. If you cannot use it, try looking on Boost's Implementation.

我可以给你一个如何使用std::function的示例:

I can give you an example of how to use the std::function:

bool MyFunction(int i)
{
    return i > 0;
}

std::function<bool(int)> funcPointer = MyFunction;

使用此方法,可以大大提高代码的可靠性.针对您的问题,具体是:

Using this you will drastically improve your code reliability. As of your problem, specifically:

class A
{
public:
    std::function<int*(const int&)> fun;
    A(std::function<int*(const int&)> f) : fun(f) {}
};

class B
{
private:
    float r;
    int *f(const int &t)
    {
        return new int(int(r) + t);
    }
    A *a;
    B()
    {

        std::function<int*(const int&)> tempFun = std::bind(&B::f, this, _1);
        a = new A(tempFun);
    }
};

您必须添加以下名称空间:

You have to add the following namespace:

using namespace std::placeholders;

这篇关于将成员函数分配给函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆