将非静态成员函数作为参数传递

Passing Non-Static Member Function as argument

本文关键字:参数传递 函数 静态成员      更新时间:2023-10-16

SalesMap.h 摘录-

typedef BST<Sales> BinarySearchTree;//type defined for Sales_Map construction
typedef map<Date, BinarySearchTree> sales_map;//type defined for map construction
sales_map Sales_Map;

销售地图.cpp摘录-

最高和设置高都是公开的

void SalesMap::Highest(){
    void (SalesMap::*SetHighPTR)(Sales);//create non-static function pointer
    SetHighPTR = &SalesMap::SetHigh; //assign address of function void SetHigh(Sales sales)
    //it is an iterator to a specific element in Sales_Map
    it->second.InSearch(&SetHighPTR); // pass SetHigh into BST object function InSearch
}
void SalesMap::SetHigh(Sales sales)//test input sales object against global highprice variable
{
    double price = sales.GetPrice();
    if(price < high)
        high = price;
}

BST.h

Public:
     void InSearch(void (*f)(T) );//calls recursive InSearch function
Private:
      void InSearch(node*& leaf, void (*f)(T) );
template <class T>//public InSearch
void BST<T>::InSearch( void (*f)(T) )
{
    InSearch(root, (*f));
}
template <class T>//Private InSearch
void BST<T>::InSearch(node*& leaf, void (*f)(T))
{
    if(leaf != NULL)
    {
        InSearch(leaf->left);
        (*f)(key);
        InSearch(leaf->right);
    }
}

我正在尝试在 BST.h 中创建一个回调函数。我不断收到以下错误:

error C2664: 'void BST<T>::InSearch(void (__cdecl *)(T))' : cannot convert parameter 1 from 'void (__thiscall SalesMap::* )(Sales)' to 'void (__cdecl *)(T)'

不确定这个问题所需的正确语法,也无法弄清楚我应该做什么以及在哪里做。任何帮助将不胜感激

问题基本上是你试图将成员函数指针转换为函数指针,这在C++中根本不可能,因为成员函数指针总是需要一个调用它的对象。(this需要指向某个地方(

类的静态方法不需要任何对象,因此也是函数指针。

如果要使用成员函数指针,InSearch方法应具有以下参数:

template <class T>//public InSearch
void BST<T>::InSearch( void (SalesMap::*f)(T) )

然后,您需要一个类型为 SalesMap 或任何派生类的对象来调用此方法:

//Using an object pointer
(mySalesObjectPtr->*f)(key);
//No pointer
(mySalesObject.*f)(key);

当然,你可以为函数指针创建一个重载,就像你已经做过的那样,这适用于全局函数和静态方法。

本文的开头很好地概述了这两种类型的函数指针。

当您

要从成员类外部传递成员函数的函数指针时,这是一个基本示例。

class A
{
private:
    void(A::*m_myFuncPointer)(); ///declaring a private member function pointer
public:
    void init( void(A::*someFunc)() ){
        m_myFuncPointer = someFunc;    ///stores the function pointer
        (this->*m_myFuncPointer)();    ///calls the function using member function
    }  
    void execute(){
        std::cout<<"hello"<<std::endl;
    }
 };
int main()
{
    A a;
    a.init(&A::execute);
}