白天的小萤火虫

导航

第一章 C++对象

本章讨论C++在内存中是怎么组织类对象的,这是后面实现多态的基础。

关于下面的类定义,其在内存中的组成结构如下图,可见static数据是单独存放,一般数据是随着类对象走,static函数和非static函数都是单独存放,而虚函数也是单独存放,只是一个类有自己的vtable来指向这些虚函数,而每一个类对象则有一个vptr来指向这个虚表。

class point{
public:
point(
float xval);
virtual ~point();
float x() const;
static int pointcount();
protected:
virtual ostream& print(ostream& os) const;
float _x;
static int _point_count;
};
point pt;

有了上面的基础,我们考虑在继承体系中,其内存是如何组织的,一种可能的情况如下图所示,有了这个认识,对于对象切片操作以及通过指针和引用实现多态就会有比较深刻的理解。

class zooanimal{
public:
zooanimal();
virtual ~zooanimal();
virtual void rotate();
protected:
int loc;
string name;
};
class bear:public zooanimal{
public:
bear();
~bear();
void rotate();
virtual void dance();
protected:
enum Dances{};
Dances dances_known;
int cell_block;
};
bear b(
"yogi");
bear
*pb = &b;
bear
&rb = *pb;

posted on 2011-02-14 20:14  白天的小萤火虫  阅读(133)  评论(0编辑  收藏  举报