这是不确定的行为?通过void cast到基地*
class Derived: public Base //No other bases!!!
{
//...
};
Derived d;
void *pv = &d;
Base *b = static_cast<Base*>(pv);
b->SomeMethod();
在一个合理的实现,只要有单继承,一个Base
和Derived
指针的位将匹配。但语言是否能保证它?
编辑:Real Purpose™是通过C层将指针传递给多态C++对象回C++回调。该对象创建为Derived,但在所述回调中作为Base使用。全文是here。
接受指出一个具体的故障情况。菲利普的回答也可以。 –
Real Purpose™是通过用'void * pv = static_cast (&d);'替换第二行来实现的。在我编写/编译/测试过这个特定情况下,然后开始思考,基类一直有虚拟方法。 –