首页 > 解决方案 > 函数指针初始化不会编译

问题描述

我正在尝试初始化函数指针变量,以便将其作为参数传递给采用函数指针的构造函数。

我已经尝试了几乎可以在网上找到的该声明的每个版本,并且所有版本都给了我编译错误。

// the functions
void *OthelloBoard::GetOptions() const { return nullptr; }
void OthelloBoard::SetOptions(const void *data) {}

// the function pointers
void *(OthelloBoard::*GetOptionsPtr)() const = &OthelloBoard::GetOptions;
void (OthelloBoard::*SetOptionsPtr)(const void *) = &OthelloBoard::SetOptions;

// the constructor 
BoardClass(void (*setOptions)(const void *), void *(*getOptions)()) {}

// the constructor call
BoardClass OthelloBoard::mClass(SetOptionsPtr, GetOptionsPtr);

我希望变量能够编译并正确传递,但我得到了这个错误:

error: cannot initialize a variable of type 'void (OthelloBoard::*)(const void *)' with an rvalue of type 'void (*)(const void *)'

void (OthelloBoard::*SetOptionsPtr)(const void *) = &OthelloBoard::SetOptions;
                     ^                              ~~~~~~~~~~~~~~~~~~~~~~~~~

标签: c++function-pointers

解决方案


推荐阅读