在下面的代码中,我不明白为什么“Derived1”需要与“Derived3”相同的内存量。另外Derived 4的size为16有没有什么特殊意义。
#include <iostream>
using namespace std;
class Empty
{};
class Derived1 : public Empty
{};
class Derived2 : virtual public Empty
{};
class Derived3 : public Empty
{
char c;
};
class Derived4 : virtual public Empty
{
char c;
};
class Dummy
{
char c;
};
int main()
{
cout << "sizeof(Empty) " << sizeof(Empty) << endl;
cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;
cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;
return 0;
}
这段代码的输出是:
sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 8
sizeof(Derived3) 1
sizeof(Derived4) 16
sizeof(Dummy) 1
最佳答案
class
的 sizeof
必须为 1 或更大,否则指针运算会严重中断,并且 class
的数组元素会都占用相同的内存。
因此 sizeof(Derived1)
至少为 1,sizeof(Empty)
也是如此。 空基优化 意味着派生类的大小实际上为零。
sizeof(Derived3)
也可以是 1,因为单个成员是 char
。请注意,编译器在这里再次利用空基优化。
多态 类(即那些包含 virtual
关键字的类)具有更大的大小,因为您的编译器实现了多态行为的要求。
关于c++ - 我不明白为什么 'Derived1' 需要与 'Derived3' 相同的内存量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380901/