#include <iostream>
using namespace std;
class Widget
{
public:
Widget()
{
pa[0] = &Widget::f;
pa[1] = &Widget::g;
pa[2] = &Widget::i;
pa[3] = &Widget::j;
}
void select(int idx)
{
(this ->* pa[idx])();
}
private:
void f(){cout<<"void f()"<<endl;}
void g(){cout<<"void g()"<<endl;}
void i(){cout<<"void i()"<<endl;}
void j(){cout<<"void j()"<<endl;}
enum {cnt = 4};
void (Widget::*pa[cnt])() = {f, g, i, j};
};
/*正常的函数指针数组
void f(){cout<<"void f()"<<endl;}
void g(){cout<<"void g()"<<endl;}
void i(){cout<<"void i()"<<endl;}
void j(){cout<<"void j()"<<endl;}
void (*pa[])() = {f, g, i, j};
*/
int main()
{
Widget w;
w.select(2);
return 0;
}
指向数据成员和成员函数的指针
#include <iostream>
using namespace std;
class B
{
public:
void func()
{
cout<<"void func()"<<endl;
}
string name;
};
int main()
{
string B::*ps = &B::name;//注意这个指针的写法,从始至终没有出现过对象,都是和类相关的
//其实本质就是从类的起始地址的偏移量
B b;
b.*ps = "china";
cout<<b.*ps<<endl;
void (B::*pf)(void) = B::func;
(b.*pf)();
/****************************************************************************/
B *pb = new B;//如果B是这么来的
pb ->* ps = "canada";
cout<<pb ->* ps<<endl;
(pb ->*pf)();
// '.*' 和 '->*':Member pointer selector 成员指针选择器
}