[英]How does C++ compiler know the size of a object with superclasses
Exactly as the question states! 正如问题所述!
Let's say I have the following snippet 假设我有以下代码段
class A
{
int x;
int y;
}
class B : public A
{
int z;
}
class C
{
A a;
public C(A a) : a(a){}
}
What would happen if I called C's constructor with a B class, would it copy it's A part data in the class? 如果我用B类调用C的构造函数会发生什么,它会复制它在类中的部分数据吗? Or also keep it's B data somewhere? 或者还保留它的B数据?
Thanks in advance! 提前致谢! It might be a stupid question but I never understood actually. 这可能是一个愚蠢的问题,但我实际上从未理解过。
If you pass an instance of B
to the C
constructor that takes an A
by value, the B
instance will be sliced, and just the A
part will remain. 如果将B
的实例传递给采用A
by值的C
构造函数,则B
实例将被切片,并且只保留A
部分。 So : 所以:
would it copy it's A part data in the class? 它会复制它在课堂上的部分数据吗?
this. 这个。
So, specifically, there is no way to turn the C::a
member back into a B
instance with the same value for z
as the original B
instance - that information has been lost during the (irreversible) slicing operation. 所以,具体而言,没有办法打开C::a
构件回一个B
实例具有相同值用于z
作为原始B
实例-该信息具有(不可逆的)切片操作过程中丢失了。
What would happen if I called C's constructor with a B class, would it copy it's A part data in the class? 如果我用B类调用C的构造函数会发生什么,它会复制它在类中的部分数据吗?
Yes. 是。 This is known as slicing - the argument is created using A
's copy constructor, which just copies the A
subobject. 这称为切片 - 参数是使用A
的复制构造函数创建的,它只复制A
子对象。
Or also keep it's B data somewhere? 或者还保留它的B数据?
No. 没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.