您的位置:首页 > 编程语言 > C语言/C++

c++ 成员函数作为函数指针参数传入

2012-08-19 18:56 621 查看
在编写二叉树图形化演示程序的时候,要实现二叉树的前序,中序、后序遍历,遍历的时候传入一个函数指针来处理遍历到的节点

void XXXX::InOrder(TreeNode * Tree,int (*func)(TreeNode * Tree))
{
if( ! Tree ) return ;

InOrder(Tree->lchild,func);
if ( !func(Tree) ) return;
InOrder(Tree->rchild,func);}
}


另外有一个成员函数:目的是作为函数指针(节点处理函数)

int XXXX::VisitList(TreeNode *Tree)
{
//Do Sth
return 1;
}


但是在c++里面,将成员函数作为函数指针传入的时候会提示类型不匹配调用的时候 PreOrder(m_pTree,VisitList);会有下面的错误提示:

error C2664: 'PreOrder' : cannot convert parameter 2 from 'int (struct tagTreeNode *)' to 'int (__cdecl *)(struct tagTreeNode *)'
None of the functions with this name in scope match the target type


这个是因为成员函数和函数指针处理的编译模式 不一样

一个是thiscall,一个是__cdecl

解决方案:

修改有参数为成员函数指针的函数如下:

void XXXX::PreOrder(TreeNode * Tree,int (CMyTreeDlg::*func)(TreeNode * Tree))
{
if( ! Tree ) return ;

if ( !( this->*func)(Tree) )
return;
PreOrder(Tree->lchild,func);
PreOrder(Tree->rchild,func);
}


在需要调用PerOrder函数地方取函数指针

void XXXX::OnButtonPreorder()
{
int (CMyTreeDlg::*pfunc)(TreeNode *); //声明一个和参数类型一样的函数指针

pfunc =& CMyTreeDlg::CreateVisitList; //指针指向要调用的函数
PreOrder(m_pTree,pfunc);  //将声明的指针看作参数传入
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: