将非静态成员函数作为参数传递
Passing Non-Static Member Function as argument
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);
}
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 如何传递带有通过引用传递的结构参数的函数?
- 如何在 c++ 中将函数作为参数传递?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 将函数作为参数传递以避免重复代码
- 如何在类(C )中作为参数传递函数