多态性和类型转换

2 c++ polymorphism

我对多态性的一个方面感到困惑.请考虑以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题如下:在线上分配了CBase* pba = new CDerived;一个CDerived类型(24字节)的对象,但正如你所看到的,sizeof(*pba) = 8字节.CDerived对象的其他16个字节发生了什么pba?我也试过这个:

std::cout << "pba->a = " << pba->a << std::endl;
Run Code Online (Sandbox Code Playgroud)

但后来得到了编译错误,意思是pba真的没有指向类型的对象CDerived.那么这里发生了什么?内存泄漏?

R. *_*des 10

sizeof是一个编译时构造.它无法知道运行时类型,因此它只考虑编译时类型,即CBase&.

pba->a由于类似的原因不编译:编译时类型pbaCBase*,并且CBase没有a成员.这就是静态类型语言的工作原理.如果要使用CDerived成员,则需要具有类型的变量CDerived(或引用或指向它的变量).

然而,CDerived物体仍然存在.你可以看到,如果你将指针转换为指向CDerived,如dynamic_cast<CDerived*>(pba)->a.