和普通指针一样,在申明成员指针时我们也使用*来表示当前申明的名字是一个指针。
不同之处是成员指针还必须包含成员所属的类。(classname::来表示当前定义的指针可以指向classname的成员)
eg:const string Test::*pTest;
特点:成员指针只针对类的非static成员。static成员指针是普通指针。
1.定义数据成员的指针:
string Screen::* //表示指向std::string类型的Screen类成员的指针
string Screen::*ps_Streen = &Screen::contents;
2.定义成员函数的指针:
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])();