how to passing member function as parameter

S

sun

I have a tree structure defined as Nodes with parent and children. a
tree class holds traverse function and other functions.

When traversing the tree with its nodes, I 'd pass one of the function
in node, func1() as parameters, is it possible? if so, how to define that?

class Node{
.....
public:
func1();//do sth
}
class Tree{
Node* root;
..
public:
traverse(Node,func1);
}

Thanks!
 
H

hurcan solter

I have a tree structure defined as Nodes with parent and children. a
tree class holds traverse function and other functions.

When traversing the tree with its nodes, I 'd pass one of the function
in node, func1() as parameters, is it possible? if so, how to define that?

class Node{
....
public:
func1();//do sth}

class Tree{
Node* root;
..
public:
traverse(Node,func1);

}

Thanks!
Yes by using to pointer to member functions and here is a compilable
example.

#include <iostream>

class Node{

public:
void func1(){std::cout<<"called";}//do sth
};
class Tree{
public:
Node* root;
void traverse(Node* node,void (Node::*funcptr)()){
(node->*funcptr)();
}

};
int main()
{
Node* nodeptr = new Node;
Tree tree;
tree.traverse(nodeptr,&Node::func1);
}

also check out http://www.parashift.com/c++-faq/pointers-to-members.html
 
S

Sun

Thank you very much, very much indeed!
It would take me days of reading and searching without your tips.

My code is working now.
Nice day,

Sun
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,955
Messages
2,570,117
Members
46,705
Latest member
v_darius

Latest Threads

Top