int a=4; int *p = &a;//指针p指向a,p是一种绝对指针,只需通过p就能找到a;
如果有一种指针指向一个类对象的成员,那么在类对象没有创建之前是无发获得类对象的地址包括类成员的地址;
但类成员的地址之间是有某种关联的,如果假设指向类对象成员的指针只代表对象空间内的一定偏移量,为了取得
指针所指向的内容,必须用*来获取,但它只是类对象内的一定偏移量,是以类对象为基址的相对地址,所有还需要
类对象的地址。
objectpointer->*pointertomember = 48;
object.*pointertomember = 48;
如何定义类对象成员指针呢,其实和定义普通的指针一样,只是所指向的对象有所特殊,指针需要类和域操作符::来修饰
membertype objectclass::*pointertomember ;
另外,成员指针是受限制的,它们仅能被制定类内确定的位置,不能像普通指针一样,增减、比较操作。
#include<iostream>
using namespace std;
class Data{
public:
int a,b,c;
void print()const{
cout << "a=" << a << endl << "b=" << b << endl
<< "c=" << c << endl;
}
};
int main()
{
Data d,*dp =&d;
printf("%p\n",dp);
int Data::*p = &Data::a;//只是一个类而不是类对象,所以无法获得确切的地址,但
printf("%p\n",p); //能获得a在类内的相对地址
printf("%p\n",&d.a);
dp->*p = 1;
p = &Data::b;
printf("%p\n",p);
dp->*p = 2;
p = &Data::c;
printf("%p\n",p);
dp->*p = 3;
d.print();
return 0;
}
类成员函数指针
#include<iostream>
using namespace std;
class Widget{
public:
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 k(int) const {cout << "Widget::k()"<<endl;};
};
typedef void (Widget::*Widgetmemberpointer)(int) const;
int main()
{
void (Widget::*w)(int) const = &Widget::f;
Widgetmemberpointer wmp = &Widget::g;
Widget wi,*wp;
wp = &wi;
(wi.*w)(1);
(wp->*wmp)(2);
}