| View previous topic :: View next topic |
| Author |
Message |
morz Guest
|
Posted: Mon Sep 18, 2006 8:32 am Post subject: function pointer in class |
|
|
#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;
} |
|
| Back to top |
|
 |
Thomas Tutone Guest
|
Posted: Mon Sep 18, 2006 8:41 am Post subject: Re: function pointer in class |
|
|
morz wrote:
| Quote: | #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 |
|
| Back to top |
|
 |
morz Guest
|
Posted: Mon Sep 18, 2006 9:00 am Post subject: Re: function pointer in class |
|
|
Thanks,it works!
How about if I dont want using static function,because I want my hello
function can access class member.Thanks. |
|
| Back to top |
|
 |
morz Guest
|
Posted: Mon Sep 18, 2006 9:09 am Post subject: Re: function pointer in class |
|
|
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);
}
}; |
|
| Back to top |
|
 |
bharath.donnipad@gmail.co Guest
|
Posted: Mon Sep 18, 2006 9:10 am Post subject: Re: function pointer in class |
|
|
morz wrote:
| Quote: | Wow ! it works! Thanks a lot.
|
Firstly I dont understand why the initial code in first mail doesn't
work. Can someone please explain? |
|
| Back to top |
|
 |
Guest
|
Posted: Mon Sep 18, 2006 9:10 am Post subject: Re: function pointer in class |
|
|
morz wrote:
| Quote: | 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);
} |
|
| Back to top |
|
 |
morz Guest
|
Posted: Mon Sep 18, 2006 9:10 am Post subject: Re: function pointer in class |
|
|
| Wow ! it works! Thanks a lot. |
|
| Back to top |
|
 |
|