指向類成員(成員變數和成員方法)的指標
1:定義一個指標指向類的普通成員變數
示例代碼1
點擊查看代碼
class Test2{
public:
int ma;
static int mb;
void f1(){cout<<"Test::void f1()"<<endl;}
static void static_f(){
cout<<"Test::void static_f()"<<endl;
}
};
int Test2::mb=0;
int main(){
int *p = &Test2::ma;
return 1;
}
點擊查看代碼
需要這樣定義
int Test2::*p = &Test2::ma;
*p=30;//這樣操作沒有意義,因為ma是需要基于物件的,所以需要這樣
Test2 t;
int Test2::*p = &Test2::ma;
t.*p=30;
或者
Test2 *pt=new Test2();
int Test2::*pp = &Test2::ma;
pt->*pp=40;
或者
int *p3=&Test2::mb;
*p3=50;
2:定義一個函式指標指向類的成員函式
void (*pf)() = &Test2::f1(); 編譯報錯
要明確的指出pf是指向Test2類中函式的函式指標,如下
void(Test2::*pf)()=&Test2::f1();
如果通過函式指標呼叫函式?需要依賴物件,如下
Test2 t3;
Test2 p4=new Test2();
t3.pf(); //*解參考
(p4->*pf)();// *解參考
3:定義函式指標指向類的靜態成員方法
void (pf2)() = &Test2::static_f;
(pf2)();
完整示例代碼如下
點擊查看代碼
class Test2{
public:
int ma;
static int mb;
void f1(){cout<<"Test::void f1()"<<this->ma<<endl;}
static void static_f(){
cout<<"Test::void static_f()"<< mb<<endl;
}
Test2(int _ma):ma(_ma){}
};
int Test2::mb=0;
int main(){
Test2 obj1(100);
Test2 *pObj2=new Test2(20);
//定義指標指向 類的普通成員變數
int Test2::*p = &Test2::ma;
obj1.*p=1000;
pObj2->*p=2000;
//定義指標指向 類的 靜態成員變數
int *pStatic = &Test2::mb;
*pStatic=9999;
//定義函式指標 指向 類的普通成員方法
void (Test2::*pf)()=&Test2::f1;
(obj1.*pf)();
(pObj2->*pf)();
//定義函式指標 指向 類的靜態方法
void (*pf2)() = &Test2::static_f;
(*pf2)();
return 1;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/532541.html
標籤:其他
上一篇:資料加密 - 資料庫隱私欄位組件
下一篇:冷知識:預處理字串運算子
