An example illustrating the basic uses for member function pointer array
1. The results are as follows:
The value of x in instance example: 100
hello, world 100.
2. The corresponding codes for above results:
#include <iostream>
#include <stdio.h>
using namespace std;
class Example {
public:
Example(){
this->x = 10;
}
~Example(){}
int print(int x)
{
printf("hello world %d.\n", this->x);
return 0;
}
int set_x(int v)
{
this->x = v;
return 0;
}
int get_x(int x)
{
return this->x;
}
private:
int x;
};
int main ()
{
int (Example::*ptr[])(int)
{
&Example::print,
&Example::set_x,
&Example::get_x
};
Example example;
(example.*ptr[1])(100);
cout << "The value of x in instance example: " << (example.*ptr[2])(2) << endl;
(example.*ptr[0])(1);
return 0;
}
There are some notations I want to explain.
- The argument in functions such as print and get_x are useless in the execution process. And its function is to make all the member functions have some prototype.
- There are more ways to define the member function pointer array. But I just know this way.
- Lastly, The intuition of above codes from this websites.
|