类成员的指针的使用

来源:互联网 发布:windows syslog服务器 编辑:程序博客网 时间:2024/06/05 07:19

demo:

class Screen {public:      typedef std::string::size_type index;      char get() const;      char get(index ht, index wd) const;private:      std::string contents;      index cursor;      index height, width;};


1、定义数据成员的指针

string Screen::*ps_Screen = &Screen::contents;Screen::index Screen::*pindex;pindex = &Screnn::width;

2、定义成员函数的指针

char (Screen::*pmf)() const = &Screen::get; //调用操作符的优先级高于成员指针操作符,因此,包围Screen::*的括号是必要的char (Screen::*pmf2)(Screnn::index, Screen::index) const;pmf2 = &Screnn::get;

3、为成员指针使用类型别名

typedefchar (Screen::*Action)(Screen::index, Screen::index) const;/*Action是类型“Screen类的接受两个index类型参数并返回char的成员函数的指针”的名字*/Action get = &Screen::get;

4、使用成员函数指针

char (Screen::*pmf)() const = &Screen::get;Screen myscreen;char c1 = myscrenn.get();char c2 = (myscreen.*pmf)();//括号不能少Screen *pScreen = &myScreen;c1 = pScreen->get();c2 = (pScreen->*pmf)(); //括号不能少

5、使用数据成员指针

Screen::index Screen::*pindex = &Screen::width;Screen myscreen;Screen::index ind1 = myscreen.width;Screen::index ind2 = myscreen.*pindex;Screen *pScreen = &myscreen;ind1 = pScreen->width;ind2 = pScreen->*pindex;

6、使用函数指针表

class Screen {public:      typedef Screen& (Screen::*Action)();      static Action Menu[]; //函数指针表      Screen& home();      Screen& forward();      Screen& back();      Screen& up();      Screen& down();public:      enum Directions {HOME, FORWARD, BACK, UP, DOWN};      Screen& move(Directions); //在move中调用Menu数组指向的函数}Screen::Action Screen::Menu[] = { //定义和初始化函数指针表      &Screen::home,      &Screen::forward,      &Screen::back,      &Screen::up,      &Screen::down,}Screen& Screen::move(Directions cm){      (this->*Menu[cm])();      return *this;}//调用moveScreen myScreen;myScreen.move(Screen::HOME);myScreen.move(Screen::DOWN);





原创粉丝点击