[英]C++ passing pointer to child's function back to parent class
[Ubuntu,C ++ 11,g ++]
我很难理解如何将指向子类函数的指针传递回父类。
由于我所有的用例都需要一个信号处理程序来终止程序,因此我决定在我的抽象类中实现它的必要部分,并允许进行自定义处理。
因此,我希望子类能够将指向他们自己的“停止”功能版本的指针传递到“ setupSIG_Handler”方法中。 然后,“ setupSIG_Handler”将此指针分配给从信号处理程序本身调用的全局变量void(* stopFunction)()。
只会有一个孩子的实例。
下面是我的代码(仅显示相关部分),并且在setupSIG_Handler签名中以及从Derived类的构造函数对其进行调用时,我从编译器中收到语法错误。
谁能帮助我了解如何进行这项工作?
干杯,
小憩
Abstract.h
class Abstract {
protected:
void setupSIG_Handler(void (*myStopFunction)()) <= ERROR
public:
virtual void stop() = 0;
}
Abstract.cpp
void (*stopFunction)();
static void sigSIGINThandler(int sigNum, siginfo_t *siginfo, void *context) {
std::cerr << std::endl << "Shutting Down Robot" << std::endl;
(*stopFunction)();
exit(0);
}
void NXT::setupSIG_Handler(void (*myStopFunction)()) { <= ERROR
stopFunction = myStopFunction;
struct sigaction ourSIGINTrecord, oldSIGINTrecord;
ourSIGINTrecord.sa_sigaction = &sigSIGINThandler;
sigaction(SIGINT, &ourSIGINTrecord, NULL);
}
Derived.h
class Derived : Abstract {
public:
virtual void stop();
}
Derived.cpp
Derived::Derived() {
setupSIG_Handler(&Derived::stop); <= ERROR
}
void Derived::stop(){
setMotors(0);
}
编辑 @Sean&@Josh:非常感谢您的解释。 是的,我了解静态方法和实例化方法之间的区别,只是不熟悉如何在C ++中处理它。
您正在尝试将指向成员函数的指针传递给只采用指向C样式函数的指针的方法,这会给您带来麻烦。
这样想,当您尝试调用派生的stop
方法时, sigSIGINThandler
函数将如何知道要针对哪个实例stop
。
要解决此问题,请使用std :: function类表示回调:
#include <functional>
std::function<void(void)> stopFunction;
static void sigSIGINThandler(int sigNum, siginfo_t *siginfo, void *context)
{
std::cerr << std::endl << "Shutting Down Robot" << std::endl;
stopFunction();
exit(0);
}
void NXT::setupSIG_Handler(std::function<void(void)> myStopFunction)
{
stopFunction = myStopFunction;
struct sigaction ourSIGINTrecord, oldSIGINTrecord;
ourSIGINTrecord.sa_sigaction = &sigSIGINThandler;
sigaction(SIGINT, &ourSIGINTrecord, NULL);
}
现在,您可以这样注册您的处理程序(使用lambda):
Derived::Derived()
{
auto handler=[this]{stop();};
setupSIG_Handler(handler);
}
或者,您可以使用bind
。
setupSIG_Handler
使用指向函数的指针,但是Derived::Derived
尝试将指针传递给(非静态)成员函数。 指向函数的指针与指向成员函数的指针的类型不同,因为(非静态)成员函数采用隐式this
参数。
请参阅C ++常见问题解答 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.