1 本文使用工具位visual studio2017,32位编译,不同厂家的编译器结果可能位置略有不同(虚函数表指针位置不同)
2 代码在结尾,打印内存布局的方式在结尾。
class father
{
public:
father() { };
virtual ~father() {};
char c;
int d;
protected:
private:
};
class child1//: public father
{
public:
virtual void vFunc() { cout << "child" << endl; }
int f;
};
class child2//: public father
{
public:
//virtual void vFunc() { cout << "child2" << endl; }
int f;
};
class son : public child2
{
public:
//virtual void vFunc() { cout << "son" << endl; }
int g;
};
int main() {
son testSon;
child2 *testChild2 = &testSon;
cout << testChild2 << endl;
cout << &testSon << endl;
}
1>class son size(8):
1> +---
1> 0 | +--- (base class child2)
1> 0 | | f
1> | +---
1> 4 | g
1> +---
1>
1>class son size(12):
1> +---
1> 0 | +--- (base class child2)
1> 0 | | {vfptr}
1> 4 | | f
1> | +---
1> 8 | g
- +---
1>class son size(12):
1> +---
1> 0 | +--- (base class child2)
1> 0 | | {vfptr}
1> 4 | | f
1> | +---
1> 8 | g
1> +---
1>
1>class son size(12):
1> +---
1> 0 | {vfptr}
1> 4 | +--- (base class child2)
1> 4 | | f
1> | +---
1> 8 | g
- +---
1>class son size(12):
1> +---
1> 0 | {vbptr}
1> 4 | g
1> +---
1> +--- (virtual base child2)
1> 8 | f
- +---
1>class son size(16):
1> +---
1> 0 | {vbptr}
1> 4 | g
1> +---
1> +--- (virtual base child2)
1> 8 | {vfptr}
1>12 | f
- +---
1>class son size(16):
1> +---
1> 0 | {vbptr}
1> 4 | g
1> +---
1> +--- (virtual base child2)
1> 8 | {vfptr}
1>12 | f
1> +---
1>
1>class son size(16):
1> +---
1> 0 | {vfptr}
1> 4 | {vbptr}
1> 8 | g
1> +---
1> +--- (virtual base child2)
1>12 | f
- +---
1>class son size(16):
1> +---
1> 0 | {vbptr}
1> 4 | g
1> +---
1> +--- (virtual base child2) 1份父类
1> 8 | {vfptr}
1>12 | f
- +---
1>class son size(20):
1> +---
1> 0 | {vfptr}
1> 4 | {vbptr}
1> 8 | g
1> +---
1> +--- (virtual base child2)
1>12 | {vfptr}
1>16 | f
1> +---
1>class son size(28):
1> +---
1> 0 | +--- (base class child2)
1> 0 | | {vfptr}
1> 4 | | {vbptr}
1> 8 | | f
1> | +---
1>12 | g
1> +---
1> +--- (virtual base father)
1>16 | {vfptr}
1>20 | c
1> | <alignment member> (size=3)
1>24 | d
1> +---
打印内存布局配置方式: