
类成员指针用法:
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 }
估计成员指针中存放的是该成员在对象中的相对偏移。




近期评论