C++对象模型探索 / 子类的内存布局
生活随笔
收集整理的這篇文章主要介紹了
C++对象模型探索 / 子类的内存布局
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、栗子
#include <iostream>class Father { public:Father(){std::cout << "I am father,this is " << this << std::endl;}public:void func_father(){std::cout << "傳入 Fahter::func_father() 的 this 指針是 " << this << std::endl;} private:int father; };class Mother { public:Mother(){std::cout << "I am Mother,this is " << this << std::endl;}public:void func_mother(){std::cout << "傳入 Mother::func_mother() 的 this 指針是 " << this << std::endl;} private:int mother; };class Son : public Father,public Mother { public:Son(){std::cout << "I am Son,this is " << this << std::endl;}public:void func_Son(){std::cout << "傳入 Son::func_Son() 的 this 指針是 " << this << std::endl;} private:int son; };int main() {Son s;std::cout << std::endl;s.func_father();s.func_mother();s.func_Son();return 0; }結果:
I am father,this is 0xffffcc14 I am Mother,this is 0xffffcc18 I am Son,this is 0xffffcc14傳入 Fahter::func_father() 的 this 指針是 0xffffcc14 傳入 Mother::func_mother() 的 this 指針是 0xffffcc18 傳入 Son::func_Son() 的 this 指針是 0xffffcc14二、詳解
? ? ? ? 由上述代碼可知,子類的內(nèi)存布局如下圖所示,?
? ? ? ? 由于“Son”繼承順序是“Father”、“Mother”,所以內(nèi)存布局中 Father 類排布在起始位置,之后是 Mother 類,最后才是 Son 類自身的變量(當然,初始化順序也是 Father 、Mother,最后才是 Son )。
? ? ? ? 具體為什么內(nèi)存布局中只有變量而沒有函數(shù)的原因,請看鏈接。?
? ? ? ? 最后還有一個問題,為什么 Son 的對象調(diào)用可以調(diào)用 Father 和 Mother 類的函數(shù)呢?因為編譯器在調(diào)用 Father 和 Mother 的函數(shù)時,調(diào)整了傳入到?Func_Father 和 Func_Mother 函數(shù)的 this 指針,使 this 指針是各個函數(shù)所在類的對象的 this 指針,從而達到了調(diào)用各個類的函數(shù)的目的。
?
(SAW:Game Over!)
總結
以上是生活随笔為你收集整理的C++对象模型探索 / 子类的内存布局的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux socket API / b
- 下一篇: Cpp 对象模型探索 / 编译器为对象创