我对这里的函数指针的使用感到困惑。 我有一个名为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已经是该类的成员,因此不应该产生任何错误。我的理由是正确的吗?
P.S.It还不清楚如何在不传递对给定类的引用的情况下实现这样的实现。
答案 0 :(得分:1)
除了静态成员函数之外,这是一个带有“普通”函数的完整示例:
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();
}