直接使用成员函数的函数指针

Direct Use of Function Pointers of a member function

本文关键字:函数 指针 成员      更新时间:2023-10-16

我对这里函数指针的用法有点困惑。我有一个叫做gc()的方法,定义如下:

static const float *gc( int i)
{
    return( &H[ BufSize*i ] );
}

这里的H是浮点指针。我现在所做的是使这两个(H和gc())都成为这样一个类的成员:

class named
{
float* H;
static const float *gc( int i)
    {
        return( &H[ BufSize*i ] );
    }
int newMethod()
{   
int newd = external_function(const float* (gc*)(int), <other-parameters>);
return newd;
}
};

然而,由于H和gc()现在都是成员,语法没有改变,但现在我很困惑如何从外部函数调用这个(成员)函数指针,像这样:

int external_function(const float* (gc*)(int), <other-parameters>);

这实际上是一个外部函数,我从类内部调用它。既然gc和H已经是类的成员,这应该不会产生任何错误。我的推理对吗?

注:在不传递对给定类的引用的情况下,这样的实现如何是正确的,这一点也不清楚。

下面是一个带有静态成员函数的"普通"函数的完整示例:

void external_function(const float* (*f)(int)){ cout << *(f(3)) << endl; }
// declaration of a "normal" function with the same signature as gc; 
// (declaring it here is needed because we refer to it in named::newMethod(),
const float *globally_visible_func(int i2);
class named
{
public: // need to make H accessible for externalgc
    static float H[];
private:
    static const float *gc( int i)
    {
        cout << "static function named::gc, arg was " << i << endl;
        return( &H[i] );
    }
public:
    int newMethod()
    {
        H[3] = 123;
        // Use a pointer to the static member function gc as argument
        external_function(gc);
        // now use a pointer to a "normal" function as argument. There
        // is no difference.
        external_function(globally_visible_func);
    }
};
// A pointer to this "normal" function is used as argument above
const float *globally_visible_func(int i2) 
{
    cout << "globally_visible_func, arg was " << i2 << endl;
    return named::H + i2;
}
float named::H[100];  // must define (i.e. create and initialize) static data member
int main()
{
    named n;
    n.newMethod();
}