这个问题被勾起来的原因是听到师兄面试又被提到。本来知道这玩意,但还是想实践检验一下加深理解。
1)上酸菜:
类是创建对象的模子!
#include <iostream>
using namespace std;
class root
{
protected:
int id;
public:
root()
{
id = 1;
}
virtual void say()
{
cout << "i am the root" << endl;
}
virtual void move()
{
cout << "i can move here and there" << endl;
}
};
class leaf: public root
{
protected:
int color;
public:
leaf()
{
id = 2;
color = 999;
}
void say()
{
cout << "I am the leaf" << endl;
}
};
int main(int argc, char* argv[])
{
root r;
r.say();
leaf l;
l.say();
root* p;
p = new leaf();
//p->say();
//p->move();
return 0;
}
2)调试跟踪:
watch的皆是数据对象。(内存中包括数据和代码)
可以看到:
1)r的id之前一个__vfptr(虚函数表指针)。
2)l的color之前是一个root。注意其中的__vfptr[0]已经变成leaf::say(void)。
于是有下图,注意到l中包含一个root。
对于p和*p有:
可以看到:
0)标出的内容值都是一样。
1)p有两种解释,一个leaf或者一个虚函数表。
2)*p只有一种数据对象解释:一个root。
a)注意到源代码中定义为root* p。b)注意下面没有了color。
于是有下图:
原文链接: https://www.cnblogs.com/jiejue/archive/2012/11/02/2751924.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/67917
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!