zoukankan      html  css  js  c++  java
  • 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 }

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

  • 相关阅读:
    L1-050. 倒数第N个字符串
    全排列问题(递归)
    L2-014. 列车调度
    连通 OR 不连通(NOJ 1044)
    数三角形(codevs 3693)
    Min(BZOJ 1441)
    STL中heap用法
    军训分批(codevs 2751)
    团伙(codevs 2597)
    Subsequence(hdu 3530)
  • 原文地址:https://www.cnblogs.com/richardustc/p/3037579.html
Copyright © 2011-2022 走看看