在oops中向下倾倒

Kam*_*ian 0 c++ oop downcast

class Parent
{};
class A_child : public Parent
{
  void A_method();
};
class B_child : public Parent
{
  void B_method();
};
void main()
{
  A_child a;
  Parent *p = &a;
  B_child *b = (B_child*)&p;
  b->B_method();
}
Run Code Online (Sandbox Code Playgroud)

这段代码是用C++编写的.这是一个逻辑错误,因为我们试图将"猫"变成"狗".但它的确有效.谁能解释为什么以及如何解释?

eer*_*ika 5

谁能解释为什么以及如何解释?

Parent是的基B_child,因此从类型转换Parent *pB_child*被良好地形成.但是,只有在p实际指向B_child实例的基础子对象时,才会定义通过此转换指针访问指向对象的行为.

前提条件不成立,因此程序的行为未定义.可能的行为包括,但都不保证:

 - working
 - not working
 - random output
 - non-random output
 - the expected output
 - unexpected output
 - no output
 - any output
 - crashing at random
 - crashing always
 - not crashing at all
 - corruption of data
 - different behaviour, when executed on another system
 -                    , when compiled with another compiler
 -                    , on tuesday
 -                    , only when you are not looking
 - same behaviour in any or all of the above cases
 - anything else within the power of the computer (hopefully limited by the OS)
Run Code Online (Sandbox Code Playgroud)

千万不要static_cast,reinterpret_cast或C风格的表达式转换为另一种类型,除非能证明,中投是正确的.您可以dynamic_cast在不确定的情况下使用.