#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++语言保证,出如今派生类中的基类子对象有其完整原样性,这是关键所在。
为什么要使用这样牺牲空间的布局?原因是在对象之间拷贝时。仅仅对子对象进行成员拷贝而不影响派生类中的成员。
所以当一个基类指针指向派生类时,能够顺利取得这个vptr然后调用所需的虚函数以表现多态性。
#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;
}对后继的基类指针的赋值,须要由编译器负责加上一个偏移地址。
Vertex3d v3d;
Vertex *pv;
Point2d *p2d;
Point3d *p3d;pv = &v3d;
p2d = &v3d;
p3d = &v3d;然后,对第二和第三种赋值操作。仅仅须要简单地拷贝其地址就好。由于Point2d指针和Point3d指针都指向对象v3d的起始地址。
原文:https://www.cnblogs.com/mqxnongmin/p/10628184.html