问题描述
class A
{
public:
int a;
};
class B:public A
{
public:
int b;
void foo()
{
b=a*a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A * a=new A;
a->a=10;
((B*)a)->foo();
cout<<((B*)a)->b;
}
它适用于 b = 100
,但我不知道它的工作原理。 b
存储在哪里?我只是不知道它的调用到谷歌它。
It's working for b=100
, but I dont know by which rules it works. Where is b
stored? I just don't know how its called to google it.
推荐答案
基本上,这里发生的是未定义的行为。它没有特殊的名字;很可能是被称为编程错误。您的类 A
的内存布局是:
Basically, what is happening here is undefined behaviour. It doesn't have a special name; most likely it is called a programming mistake. The memory layout of your class A
is:
int a;
B
的内存布局是: / p>
The memory layout of B
is:
int a;
int b;
所以在你的情况下,你只需为 a
但是你很幸运,空间立即之后它是免费的(以便没有其他信息被覆盖),并且它没有边界在未分配的空间(否则,当尝试写入未分配的页面时可能会发生故障) 。因此, b
存储在可用空间中。
So in your case, you only allocate space for a
but you are lucky that the space immediately after it is free (so that no other information is overwritten) and that it doesn't border on unallocated space (otherwise, a fault might occur when trying to write to an unallocated page). So b
is stored in free space.
总之:工作!
这篇关于通过转换基类指针设置派生类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!