C++类成员指针

和普通指针同样,在申明成员指针时咱们也使用*来表示当前申明的名字是一个指针。函数

不一样之处是成员指针还必须包含成员所属的类。(classname::来表示当前定义的指针能够指向classname的成员)this

eg:const string Test::*pTest;指针

特色:成员指针只针对类的非static成员。static成员指针是普通指针。get

1.定义数据成员的指针:string

string Screen::* //表示指向std::string类型的Screen类成员的指针io

string Screen::*ps_Streen = &Screen::contents;class

2.定义成员函数的指针:扩展

char (Screen::*)() const数据

char (Screen::*pmf)() const = &Screen::get:index为在类Screen中定义的类型(下同)static

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])();

相关文章
相关标签/搜索