标签:style class blog c code ext
在C++继承模型中,一个派生类对象表现出来的东西,是其自己的成员加上其基类成员的总和。但这些成员如何摆放,标准并未强制规定。一般而言,先摆放基类成员,内存向高地址增长。#include <iostream> #include <vector> using namespace std; class Foo { public: int val; char bit1, bit2, bit3; }; class A { public: int val; char bit1; }; class B : public A { public: char bit2; }; class C : public B { public: char bit3; }; int main() { cout << "size Foo = " << sizeof(Foo) << endl; cout << "size C = " << sizeof(C) << endl; system("pause"); return 0; }
#include <iostream> #include <vector> using namespace std; class Foo { public: int x; }; class Bar : public Foo { public: int y; virtual void func() {} }; int main() { Bar bar; cout << &bar << endl; cout << &bar.x << endl; cout << &bar.y << endl; system("pause"); return 0; }
#include <iostream> #include <vector> using namespace std; class A { public: int x; }; class B { public: int y; }; class C : public A, public B { public: int z; }; int main() { C c; A *pa = &c; B *pb = &c; cout << &c << endl; cout << pa << endl; cout << pb << endl; system("pause"); return 0; }
// 伪代码 pb = (B *)(((char *)&c) + sizeof(A))
标签:style class blog c code ext
原文地址:http://blog.csdn.net/nestler/article/details/26804243