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 }

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

  • 相关阅读:
    exkmp
    欧拉通路、回路
    你有多久没有看过星星
    trie树模板(统计难题)
    SPFA(热浪)
    codevs1958 刺激
    洛谷1290 欧几里得的游戏
    洛谷1016 旅行家的预算
    Spfa算法模板
    Tyvj2017清北冬令营入学测试
  • 原文地址:https://www.cnblogs.com/richardustc/p/3037579.html
Copyright © 2011-2022 走看看