我对多态性的一个方面感到困惑。请考虑以下代码:
#include <iostream>
class CBase {
virtual void dummy() {}
};
class CDerived: public CBase {
public:
int a,b,c,d;
CDerived (): a(1),b(2),c(3),d(4) { }
};
int main () {
CBase* pba = new CDerived;
std::cout << "sizeof(CBase) = " << sizeof(CBase) << std::endl; // prints 8
std::cout << "sizeof(CDerived) = " << sizeof(CDerived) << std::endl; // prints 24
std::cout << "sizeof(*pba) = " << sizeof(*pba) << std::endl; // prints 8 (?)
return 0;
}
我的问题如下:在行上分配了一个类型(24 字节)CBase* pba = new CDerived;
的对象CDerived
,但正如您所看到的,sizeof(*pba) = 8
字节。CDerived
指向的对象的其他 16 个字节发生了pba
什么?我也试过这个:
std::cout << "pba->a = " << pba->a << std::endl;
但随后出现编译错误,这意味着pba
实际上并不指向 type 的对象CDerived
。那么这里发生了什么?内存泄漏?