类成员的指针的使用

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、为成员指针使用类型别名

typedef
char (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;
}

//调用move
Screen myScreen;
myScreen.move(Screen::HOME);
myScreen.move(Screen::DOWN);





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值