定义:指定对象的指针,我们可以通过箭头操作符指定成员。有时我们希望直接获取成员的指针,然后从一个对象或别的对象获得该成员,这时就需要用到成员指针。成员指针,包含类的类型以及成员的类型。
特点:成员指针只针对类的非static成员。static成员指针是普通指针。
1.定义数据成员的指针:
string Screen::* //表示指向std::string类型的Screen类成员的指针
string Screen::*ps_Streen = &Screen::contents;
2.定义成员函数的指针:
1)函数形参的类型和数目,包括成员是否为const
2)返回类型
3)所属类的类型
char (Screen::*)() const
char (Screen::*pmf)() const =
&Screen::get:index为在类Screen中定义的类型(下同)
typedef std::string::size_type index;
char (Screen::*pmf)(Screen::index, Screen::index) const
3.类型别名(typedef)可以使成员指针更容易扩展阅读
//Screen类的接受两个index类型形参并返回char的成员函数的指针
typedef char (Screen::* Action)(Screen::index, Screen::index)
const
//可以使用成员指针函数类型来声明函数形参和函数返回类型
Screen& action(Screen&, Action = &Screen::get)
4.成员函数指针的使用
char c = (pScreen->*pmf)();
5.数据成员指针的使用
Screen::index Screen::*pindex =
&Screen::width;:Screen::index ind2 = pScreen->*pindex;
6.定义成员函数指针表
typedef Screen& (Screen::*Action)();
Screen::Action Screen::Menu[] = {&Screen::home,
&Screen::forward, &Screen::back, &Screen::up,
&Screen::down}
7.成员函数指针表的使用
(this->*Menu[cm])();