C++类成员指针

类成员指针用法:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Test{
 5     public:
 6         static int x; //static member
 7         int y;
 8         int foo(int i){
 9             return i;
10         }
11         int Test::* get_y_ptr(){
12             return &Test::y;
13         }
14 };
15 int Test::x = 0;
16 
17 int main(){
18     cout<<hex<<&(Test::x)<<endl; //we can get address of static member directly
19     Test t;
20     Test * pt = &t;
21     t.y = 0xdeadbeef;
22     int Test::* p1 = &Test::y; //get member pointer of x
23     cout<<hex<<t.*p1<<endl;
24     cout<<hex<<pt->*p1<<endl;
25 
26     int Test::* p2 = t.get_y_ptr(); //get member pointer through function call
27     cout<<hex<<t.*p2<<endl;
28     cout<<hex<<pt->*p2<<endl;
29 
30     int (Test::*func)(int) = &Test::foo; //get member pointer of member function. pay attention to the position of '*'
31     cout<<(t.*func)(0)<<endl;   // '()' around 't.*func' is essential
32     cout<<(pt->*func)(0)<<endl;  // so is this case
33     return 0;
34 }

估计成员指针中存放的是该成员在对象中的相对偏移。

转载于:https://www.cnblogs.com/richardustc/archive/2013/04/23/3037579.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值