直接使用成员函数的函数指针
Direct Use of Function Pointers of a member function
我对这里函数指针的用法有点困惑。我有一个叫做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();
}
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针