function pointer in class

M

morz

#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;
}
 
T

Thomas Tutone

morz said:
#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
 
M

morz

Thanks,it works!

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

morz

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);
}
};
 
A

amparikh

morz said:
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);
}
 

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
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top