Father类:
class Father { public: virtual void Func1() { cout << "Father::Func1" << endl; } virtual void Func2() { cout << "Father::Func2" << endl; } virtual void Func3() { cout << "Father::Func3" << endl; } void Func4() { cout << "Father::Func4" << endl; } public: int x = 200; int y = 300; static int z; }; int Father::z = 0;
Mather类:
class Mather { public: virtual void Handle1() { cout << "Mother::Handle1" << endl; } virtual void Handle2() { cout << "Mother::Handle2" << endl; } virtual void Handle3() { cout << "Mother::Handle3" << endl; } public: int i = 600; int j = 800; };
Son类: public Father,public Mather
class Son:public Father,public Mather { public: void Func1() { cout << "Son::Func1" << endl; }//重写Father类的Func1(); void Handle1() { cout << "Son::Handle1" << endl; }//重写Mather类的Handle1(); virtual void Func5() { cout << "Son::Func5" << endl; }//自己新添加的虚函数 };
Son的内存分析:
注意:自己新添加的虚函数添加到第一个虚函数表中,其他重写的函数则直接在对应的虚函数表中进行替换.
此处Son类的基类为Father类和Mather类,则第一个虚函数表为Father继承下来的虚函数表,Monther类继承下来的虚函数表为第二虚函数表,所以Son类新添加的虚函数添加到第一个虚函数表中.
完整代码:
#include<iostream> using namespace std; //vs的对象内存分析:/d1 reportSingleClassLayout+类名 class Father { public: virtual void Func1() { cout << "Father::Func1" << endl; } virtual void Func2() { cout << "Father::Func2" << endl; } virtual void Func3() { cout << "Father::Func3" << endl; } void Func4() { cout << "Father::Func4" << endl; } public: int x = 200; int y = 300; static int z; }; int Father::z = 0; class Mather { public: virtual void Handle1() { cout << "Mother::Handle1" << endl; } virtual void Handle2() { cout << "Mother::Handle2" << endl; } virtual void Handle3() { cout << "Mother::Handle3" << endl; } public: int i = 600; int j = 800; }; class Son:public Father,public Mather { public: void Func1() { cout << "Son::Func1" << endl; }//重写Father类的Func1(); void Handle1() { cout << "Son::Handle1" << endl; }//重写Mather类的Handle1(); virtual void Func5() { cout << "Son::Func5" << endl; }//自己新添加的虚函数 }; typedef void(*func)(void); int main(void) { Son son; int* vptr =(int*)*(int*)&son; cout << "sizeof(son):" << sizeof(son) << endl; cout << "第一个虚函数表指针" << vptr << endl; for (int i = 0; i < 4; i++) { cout << "调用第" << i + 1 << "个虚函数:"; ((func) * (vptr + i))(); } for (int i = 0; i < 2; i++) { cout << *(int*)((int)&son + 4 + i * 4) << endl; } int* vptr2 = (int*)*(int*)((int)&son + 12); //int* vptr2 = (int*)*((int*)&son + 3);//结果一样 cout << "第二个虚函数表指针" << vptr2 << endl; for (int i = 0; i < 3; i++) { cout << "调用第" << i + 1 << "个虚函数:"; ((func) * (vptr2 + i))(); } for (int i = 0; i < 2; i++) { cout << *(int*)((int)&son + 16 + i * 4) << endl; } return 0; }
运行结果: