指针是指向一些内存地址的变量,既可以是数据的地址,也可以是函数的地址。
C++的成员指针包括数据成员指针和成员函数指针。C++的成员指针不是指向
确切的地址,而是指向类成员在类中的偏移。只有把这个偏移和具体对象的开
始地址结合,才能得到实际的地址。
#include <iostream>
#include <stdlib.h>
using namespace std;
class simple {
public:
int a;
int b;
int f(int f) {
b += f;
}
};
int main() {
//数据成员指针
int simple::*pa = &simple::a;
cout << "offset of a = " << pa <<endl;//这里输出为1,想知道为何请看《深度探索C++对象模型》,下同
simple so;
so.*pa = 4; //给a赋值
simple *sp = (simple *)malloc(sizeof(simple));
sp->a = 2;
sp->b = 10;
pa = &simple::b;
cout << "so.a = " << so.a <<endl;
cout << "sp->b = " << sp->*pa <<endl;
//成员函数指针
int (simple::*f)(int f);
f = &simple::f;
cout << "offset of f = " << f <<endl;
(sp->*f)(10); //调用成员函数
cout << "sp->b = " << sp->*pa <<endl;
return 0;
}
下面程序主要说明了如何使用成员函数指针:
#include <iostream>
using namespace std;
class widget {
private:
void f(int) const { cout << "widget::f()" <<endl; }
void g(int) const { cout << "widget::g()" <<endl; }
void h(int) const { cout << "widget::h()" <<endl; }
void i(int) const { cout << "widget::i()" <<endl; }
enum { count = 4 };
void (widget::*fptr[count])(int) const;
public:
widget() {
fptr[0] = &widget::f;
fptr[1] = &widget::g;
fptr[2] = &widget::h;
fptr[3] = &widget::i;
}
void select(int I, int J) {
if(I < 0 || I >= count)
return;
(this->*fptr[I])(J);
}
int Count() { return count; }
};
int main() {
widget w;
for(int i = 0; i < w.Count(); i++)
w.select(i, 47);
return 0;
}