C++类成员指针

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

不同之处是成员指针还必须包含成员所属的类。(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])();


转载于:https://my.oschina.net/zhaolu0607/blog/664691

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值