多级/多级继承期间对象的大小 [英] Size of objects during Multilevel/Multiple inheritance
问题描述
Below is a pseudo declaration for a multilevel inheritance.
Base class ( protected int data)
derived1 : virtual public base ( protected int data1 )
derived2 : virtual public base ( protected int data2)
derived3 : derived1,derived2 ( private int data3 )
Main(){ base b; derived1 d1; derived2 d2; derived3 d3; }
sizeof(b) // 4 which is correct as only int (4bytes)
sizeof(d1) // 12 why not 8 -> 4(base) + 4(derived)
sizeof(d2) // ??? whatever applies above should apply here
sizeof(d3) // 24 why not 12 -> 4(base) + 4(derived1/derived2) + 4(d3).
大小是否也包括虚拟表.同样,这里没有虚拟表,因为没有定义虚拟函数.请帮助澄清我的疑问.
Does size also include virtual tables also. Again here there cannot be virtual table as no virtual function defined. Please help in clarifying my doubt.
PS:到目前为止我所了解的:
PS: What I have understood till now:
Unless the function is declared virtual in base class,
base *bptr;
derived d;
bptr = &d;
bptr->fun(); // will call the base class function.
But if the fun() is declared virtual then the above code will call derived class fun().
推荐答案
首先,在上述实现中,您需要返回count
的类型而不是void
.
First of all, in your implementation above, you need to return the type of count
instead of void
.
例如,假设您已声明int count
.
然后,您需要在'postfix'版本中返回int
,在'prefix'版本中返回int&
或const int&
.
Then you need to return int
in the 'postfix' version, and int&
or const int&
in the 'prefix' version.
尝试b = a++
和b = ++a
,您将看到(当然,您需要每个函数都返回一个值).
Try b = a++
and b = ++a
, and you will see (of course, you'll need each function to return a value).
这两个版本之间的区别仅在于返回值. "prefix ++"在操作之前返回count
的值,而"postfix ++"在操作之后返回count
的值.
The difference between these two versions is only in the return value. The 'prefix++' returns the value of count
before the operation, and the 'postfix++' returns the value of count
after the operation.
此外,由于其性质,'postfix ++'可以仅返回要递增的变量的副本(例如,int
),而'prefix ++'也可以 返回该变量的引用(例如int&
).
In addition, due to its nature, the 'postfix++' can only return a copy of the variable being incremented (e.g., int
), whereas the 'prefix++' can also return a reference of that variable (e.g., int&
).
由于您没有在实现中返回任何内容,因此您无法利用这两个版本之间的差异.
Since you are not returning anything in your implementation, you cannot make any use of the difference between these two versions.
这篇关于多级/多级继承期间对象的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!