有一种特殊的指针叫做成员指针,它们通常指向一个类的成员,而不是对象中成员的特定实例。
成员指针并不是真正的指针,它只是成员在对象中的偏移量,它们分别是:.* 和 ->* 。
下面例子说明了成员指针 .* 的用法:
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 这种用法。
如果使用指向对象的指针来访问对象的成员,那么必须使用 ->* 运算符,如下程序示例:
需要注意指针的声明语法:在声明中使用了作用域解析运算符来指定指针指向的成员属于那个类。
当使用对象或对象引用来访问对象的成员时,必须使用 .* 运算符,如程序中的 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/