简体   繁体   English

C ++编译器如何知道具有超类的对象的大小

[英]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.

相关问题 c ++编译器如何知道参数是STL容器? - c++ How does compiler know that a parameter is an STL container? 为什么C / C ++编译器在编译时需要知道数组的大小? - Why does a C/C++ compiler need know the size of an array at compile time? 现代编译器如何优化 c++ 中的 function object? - How does modern compiler optimize function object in c++? C ++:编译器如何知道为每个堆栈帧分配多少内存? - C++: How does the compiler know how much memory to allocate for each stack frame? 在C ++中使用模板时,编译器如何知道要实例化多少个数据类型? - When using Templates in C++ how does the compiler know how many data-types to instantiate? C ++编译器如何知道正在使用哪种CPU架构 - How does the C++ compiler know which CPU architecture is being used 编译器如何知道不从内部锁定/解锁中优化语句? 在c ++中使用boost :: spinlocks - how does compiler know not to optimize statements from inside lock/unlock? using boost::spinlocks in c++ 我怎么知道C ++编译器是否制作了线程安全的静态对象代码? - How can I know if C++ compiler make thread-safe static object code? C ++编译器如何知道要调用哪个虚函数实现? - How does the C++ compiler know which implementation of a virtual function to call? 对象大小如何影响C ++中的数组性能? - How does object size impact array perfomance in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM