3虚函数表分析
1.帶有虛函數的類會多出四個字節的大小,這是一個指針的大小,這個指針的用途是指向虛函數表。
2.繼承是虛函數表的順序
#include <iostream>
using namespace std;
?
class H
{
??? virtual void M()
??? {
??????? cout << "H::H" << endl;
??? }
};
?
class A
{
??? //int num
??? virtual void g()
??? {
??????? cout << "A::g" << endl;
??? }
private:
??? virtual void f()
??? {
??????? cout << "A::f" << endl;
??? }
??? virtual void j()
??? {
??????? cout << "A::j" << endl;
??? }
};
?
//函數中有虛函數的情況下,這時候多出來了一個指針用于指向虛函數表
class B :public A //,public H
{
??? void g()
??? {
??????? cout << "B::g" << endl;
??? }
??? virtual void o()
??? {
??????? cout << "B::o" << endl;
??? }
??? virtual void h()
??? {
??????? cout << "B::h" << endl;
??? }
};
?
typedef void(*Fun)(void);
?
void main()
{
??? cout << sizeof(A) << endl;
??? cout << sizeof(H) << endl;
??? cout << sizeof(B) << endl;
?
??? B b;
??? Fun pFun;?? //定義一個函數指針
??? for (int i = 0; i < 5;i++)
??? {
??????? pFun = (Fun)*((int *)*(int *)(&b) + i);
??????? pFun();
??? }
?
??? cin.get();
}
運行結果:
3.分析
pFun = (Fun)*((int *)*(int *)(&b) + i);
A:分析*(int *)(&b),這里取的是b對象地址中的內容
B:(int *)*(int *)(&b)表示的是虛函數表的首地址
4.分析*(int *)(&b)
#include <iostream>
?
using namespace std;
?
void main()
{
??? int a = 10;
??? cout << &a << endl;
??? cout << *(int *)(&a) << endl;
???
??? cin.get();
}
運行結果:
?
?
?
?
?
總結
- 上一篇: 在哪里学烧烤 推荐几个学习烧烤技巧的地方
- 下一篇: 2Boost之UPD,Client an