成员指针运算符 .* 和 ->*

有一种特殊的指针叫做成员指针,它们通常指向一个类的成员,而不是对象中成员的特定实例。

成员指针并不是真正的指针,它只是成员在对象中的偏移量,它们分别是:.* 和 ->* 。

下面例子说明了成员指针 .* 的用法:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "stdafx.h"
#include <iostream>
using namespace std;
 
 
class myclass {
public :
     int sum;
     void myclass::sum_it( int x);
};
 
 
void myclass::sum_it( int x)
{
     int i;
     sum = 0;
     for (i = x; i; i--) sum += i;
}
 
 
int _tmain( int argc, _TCHAR* argv[])
{
     int myclass::*dp;        //指向 myclass 中整数类型成员变量的指针
     void (myclass::*fp)( int x);        //指向 myclass 中成员函数的指针
     myclass c;
 
 
     dp = &myclass::sum;        //获得成员变量的地址
     fp = &myclass::sum_it;    //获得成员函数的地址
 
 
     (c.*fp)(7);        //计算 1 到 7 相加的和
     cout << "summation of 7 is " << c.*dp;
 
 
     return 0;
}
运行输出:  summation of 7 is 28


在上面程序中,创建了两个成员指针 dp 和 fp 。其中 dp 指向了成员变量 sum ,fp 指向了函数 sum_it() 。

需要注意指针的声明语法:在声明中使用了作用域解析运算符来指定指针指向的成员属于那个类。

当使用对象或对象引用来访问对象的成员时,必须使用  .*  运算符,如程序中的 c.*fp 和 c.*dp 这种用法。

如果使用指向对象的指针来访问对象的成员,那么必须使用 ->* 运算符,如下程序示例:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "stdafx.h"
#include <iostream>
using namespace std;
 
 
class myclass {
public :
     int sum;
     void myclass::sum_it( int x);
};
 
 
void myclass::sum_it( int x)
{
     int i;
     sum = 0;
     for (i = x; i; i--) sum += i;
}
 
 
int _tmain( int argc, _TCHAR* argv[])
{
     int myclass::*dp;        //指向 myclass 中整数类型成员变量的指针
     void (myclass::*fp)( int x);        //指向 myclass 中成员函数的指针
     
     myclass *c, d;            //变量 c 显示是指向对象的指针
     c = &d;                    //将对一个对象的地址赋给 c
 
 
 
 
     dp = &myclass::sum;        //获得成员变量的地址
     fp = &myclass::sum_it;    //获得成员函数的地址
 
 
     (c->*fp)(7);        //计算 1 到 7 相加的和
     cout << "summation of 7 is " << c->*dp;
 
 
     return 0;
}
运行输出: summation of 7 is 28

上面程序中,变量 c 是指向 myclass 类型对象的指针,所以应该使用 ->* 运算符来访问 sum 和 sum_it() 。

成员指针是为了处理特殊情况而设计,在一般程序设计中通常不需要用到他们。



FROM: http://vipjy2008.blog.163.com/blog/static/372087672013933226346/

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值