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

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

2016-02-06 17:12 417 查看

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

标签:
c++treestruct图形c

2012-08-19 18:56
4239人阅读 评论(0)
收藏
举报



分类:
C++(11)


数据结构(13)


版权声明:本文为博主原创文章,未经博主允许不得转载。

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

[cpp]
view plain
copy

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

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

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

[cpp]
view plain
copy

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

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

[cpp]
view plain
copy

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

解决方案:

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

[cpp]
view plain
copy

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函数地方取函数指针

[cpp]
view plain
copy

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

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