[英]How to pass a member function to a function used in another member function?
I found something about my problem, but I don't already understand very well. 我发现了一些有关我的问题的信息,但是我还不太了解。 I need to do something like this:
我需要做这样的事情:
class T
{
double a;
public:
double b;
void setT(double par)
{
a = par;
}
double funct(double par1)
{
return par1 / a;
}
void exec()
{
b = extfunct(funct, 10);
}
};
double extfunct(double (*f)(double),double par2)
{
return f(par2)+5;
}
Operation and function are only for example, but the structure is that. 操作和功能仅是示例,但结构是这样。 The reason of this structure is that I have a pre-built class which finds the minimum of a gived function (it's extfunct in the example).
这种结构的原因是我有一个预构建的类,该类查找给定函数的最小值(在示例中为extfunct)。 So I have to use it on a function member of a class.
因此,我必须在类的函数成员上使用它。 I understood the difference between pointer to function and pointer to member function, but I don't understand how to write it.
我了解了函数指针和成员函数指针之间的区别,但是我不知道如何编写它。 Thanks, and sorry for the poor explanation of the problem.
谢谢,对于这个问题的拙劣解释,我们深表歉意。
Use a pointer to member function: 使用指向成员函数的指针:
struct Foo
{
void f(int, int) {}
void g(int, int) {}
void execute((Foo::*ptmf)(int, int), int a, int b)
{
// invoke
(this->*ptmf)(a, b);
}
};
Usage: 用法:
Foo x;
x.execute(&Foo::f, 1, 2); // calls x.f(1, 2)
x.execute(&Foo::g, 2, 1); // calls x.g(2, 1)
These pointers work as expected with virtual functions. 这些指针与虚函数一起正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.