A
Andy
Hi,
Sorry for the naive question. What I did here is to check the value of
pointers to member functions, and try to call these member function via
member functio pointers. But the program compiled with gcc gives out
segment fault. What's wrong with my code?
Here is the code:
#include <iostream>
using namespace std;
class A{
public:
int method1(int a, int b){ cout<<"Hello,world"; return 0; }
int method2(int a, int b) { return a + b; }
int method3(int x, int y) { return x * x;}
};
void conv_ptr(void * ptr, char* buf)
{
char * str = (char*)ptr;
int i;
for(i = 0; i < 4 ; i++)
sprintf(buf+i*2, "%.2x", str);
buf[8] = 0;
}
int main()
{
A a;
int (A::*ptr) (int, int) ;
char buf[9];
ptr = &A::method1;
conv_ptr(&ptr, buf);
cout<<"ptr ="<<buf<<endl;
cout<<(a.*ptr)(5,5)<<endl;
ptr = &A::method2;
conv_ptr(&ptr, buf);
cout<<"ptr ="<<buf<<endl;
cout<<(a.*ptr)(5,5)<<endl;
ptr = &A::method3;
conv_ptr(&ptr, buf);
cout<<"ptr ="<<buf<<endl;
cout<<(a.*ptr)(5,5)<<endl;
}
Thanks !
Andy
Sorry for the naive question. What I did here is to check the value of
pointers to member functions, and try to call these member function via
member functio pointers. But the program compiled with gcc gives out
segment fault. What's wrong with my code?
Here is the code:
#include <iostream>
using namespace std;
class A{
public:
int method1(int a, int b){ cout<<"Hello,world"; return 0; }
int method2(int a, int b) { return a + b; }
int method3(int x, int y) { return x * x;}
};
void conv_ptr(void * ptr, char* buf)
{
char * str = (char*)ptr;
int i;
for(i = 0; i < 4 ; i++)
sprintf(buf+i*2, "%.2x", str);
buf[8] = 0;
}
int main()
{
A a;
int (A::*ptr) (int, int) ;
char buf[9];
ptr = &A::method1;
conv_ptr(&ptr, buf);
cout<<"ptr ="<<buf<<endl;
cout<<(a.*ptr)(5,5)<<endl;
ptr = &A::method2;
conv_ptr(&ptr, buf);
cout<<"ptr ="<<buf<<endl;
cout<<(a.*ptr)(5,5)<<endl;
ptr = &A::method3;
conv_ptr(&ptr, buf);
cout<<"ptr ="<<buf<<endl;
cout<<(a.*ptr)(5,5)<<endl;
}
Thanks !
Andy