直接獲取類中 非static 成員函式位址的方法

2021-06-25 16:17:21 字數 1288 閱讀 4975

#includeusing namespace std;

class a

static void fun2(){}

};void fun3(){}

int main()

輸出為:1       010d1226        010d1249

試了一下用

printf("%p\n", &a::fun1);

能輸出位址。這裡不糾結了。

#include#includeusing namespace std;

int trans(string str)

class a

static void fun2(){}

};void fun3(){}

typedef void(*p)();

int main()

#include#includeusing namespace std;

int trans(string str)

class a

static void fun2()

};void fun1()

typedef void( a::*p_void_class)();//__thiscall

typedef void(*p_void_normal)();//normal

int main()

後來我看到乙個「奇怪」的現象,new乙個物件的指標,將其delete後,該指標任然能訪問其成員函式

a* p = new a;

delete p;

p->fun1();

這是為何?想了一下想明白了,就算執行p=null或者delete p;p的型別不會改變,僅僅是把物件的資料成員佔據的記憶體釋放了。既然是a*的型別,當然能訪問a裡面的成員函式,就像下面這樣

//int x=rand();

char x='a';

((a*)x)->fun1();

不管x是什麼東西,字元也好,隨機整數也好,只要是能轉化成指標型別的都能訪問fun1();

這也充分說明類中普通成員函式(有虛函式時只是多了個虛表)和類物件是分離的。所有的類物件訪問的是同樣的成員函式,和類外的普通函式沒什麼區別。乙個類物件的指標訪問成員函式時,該指標的值已經沒有任何意義,編譯器能直接根據型別找到函式的入口位址。至於如何得到類中成員函式的入口位址,前面已經講過方法,不再贅述。

C 之static類成員,static類成員函式

0.static修飾類中成員,表示類的共享資料 1.static類成員 在c primer裡面說過,static類成員不像普通的類資料成員,static類資料成員獨立於一切類物件處在。static類資料成員是與類關聯的,但不與該類定義的物件有任何關係。這句話什麼意思?就是static不會想普通類資料...

關於 autowire的問題直接獲取bean

在專案中遇到的奇怪的問題,在使用 autowire註解去呼叫乙個方法時出錯,除錯發現 autowire註解下的物件值為null。使用 autowire會將物件注入到當前類 這裡要注意首先類需要在spring的管理下 autowire才會起作用比如在類上加上註解 service componet等 加...

類的static成員

類static成員的兩個問題 如果需要在乙個類的各個物件間互動,即需要乙個資料物件為整個類而非某個物件服務,這個時候常用類成員來解決問題。1 靜態資料成員要在類外定義。class teststatic static int teststaticfunction teststatic obj priv...