By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,983 Members | 2,035 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,983 IT Pros & Developers. It's quick & easy.

function pointer in class

P: n/a
#include <cstdlib>
#include <iostream>

using namespace std;
what wrong with my code? how to correct this code to make it works?
Thanks.
class test {
public:
void hello() {
cout << "hello" << endl;
}

void ok(void (*j)()) {
(*j)();
}

void callme() {
ok(hello);
}
};

int main(int argc, char *argv[]) {
test k;
k.callme();
system("PAUSE");
return 0;
}

Sep 18 '06 #1
Share this Question
Share on Google+
7 Replies


P: n/a
morz wrote:
#include <cstdlib>
#include <iostream>

using namespace std;
what wrong with my code? how to correct this code to make it works?
Thanks.
class test {
public:
void hello() {
Change the above line to:

static void hello() {

Best regards,

Tom

Sep 18 '06 #2

P: n/a
Thanks,it works!

How about if I dont want using static function,because I want my hello
function can access class member.Thanks.

Sep 18 '06 #3

P: n/a
I try doing like this,but still error :(

class test {
public:
void hello() {
cout << "hello" << endl;
}

void ok(void (test::*j)()) {
(*j)();
}

void callme() {
ok(&hello);
}
};

Sep 18 '06 #4

P: n/a

morz wrote:
I try doing like this,but still error :(

class test {
public:
void hello() {
cout << "hello" << endl;
}

void ok(void (test::*j)()) {
(*j)();
}

void callme() {
ok(&hello);
}
};
Pointer to member functions are different from regular function
pointers.

change the code to...

void ok(void (test::*j)()) {
(this->*j)();
}

void callme() {
ok(&test::hello);
}

Sep 18 '06 #5

P: n/a
Wow ! it works! Thanks a lot.

Sep 18 '06 #6

P: n/a
morz wrote:
Wow ! it works! Thanks a lot.
Firstly I dont understand why the initial code in first mail doesn't
work. Can someone please explain?

Sep 18 '06 #7

P: n/a
On 18 Sep 2006 00:43:10 -0700 in comp.lang.c++,
"bh**************@gmail.com" <bh**************@gmail.comwrote,
>morz wrote:
>Wow ! it works! Thanks a lot.

Firstly I dont understand why the initial code in first mail doesn't
work. Can someone please explain?
Read section "[33] Pointers to member functions" in Marshall Cline's
C++ FAQ. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/

Sep 18 '06 #8

This discussion thread is closed

Replies have been disabled for this discussion.