但这些成员怎样摆放。标准并未强制规定。一般而言,低地址放基类子对象,高地址放派生类对象。
比如:
#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;
}C++语言保证。出如今派生类中的基类子对象有其完整原样性,这是关键所在。为什么要使用这样牺牲空间的布局?原因是在对象之间拷贝时。仅仅对子对象进行成员拷贝而不影响派生类中的成员。
#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;
}而派生类Bar有虚函数。编译器把它的vptr插在了类的开头处。先于基类成员摆放。
对后继的基类指针的赋值,须要由编译器负责加上一个偏移地址。
Vertex3d v3d; Vertex *pv; Point2d *p2d; Point3d *p3d;
pv = &v3d; p2d = &v3d; p3d = &v3d;
原文:http://www.cnblogs.com/claireyuancy/p/6905648.html