从Base到Derived的dynamic_cast

时间:2014-01-09 14:32:18

标签: c++ class dynamic-cast

我有一个非常普遍的问题,与c ++中的dynamic_cast有关: 我们假设我们有以下类:

class Father{ 
public:
       Father(...); // this is constructor
       //.....
       //.. Whatever code in here, not important
       ~ Father(); //destructor 
protected:
      // some protected variables
} // end of class Father


class Son:public Father {
public:
       Son(...); // this is cnostructor
       //.....
       //.. Whatever code in here, not important
       ~ Son(); //destructor 
protected:
      // some protected variables
} // end of class Son


 class Another{
 public:
      Another(...); // this is constructor
       //.....
       //.. Whatever code in here, not important
       ~ Another(); //destructor 

       AnotherMethod(Father* fatherOpj,......) //

} // end of class Another          

让我们说方法“AnotherMethod”做下一个:

   AnotherMethod(Father* fatherOpj,......)
   { 
      Son *sonObj = dynamic_cast<Son*>(fatherOpj);
    // using sonObj
   }

在主要内容中,我们执行以下操作:

  Son* son1=Null;
  //...
  son1 = new Son(.....);
 //....
  AnotherMethod(son1,....);

现在,我想知道下一个问题:那种方式 - 当我们用一个类型为Son *的指针调用AnotherMethod时,在其签名中有父亲* - 我们会失去儿子中的字段/成员(父亲没有没有) 或者通过执行dynamic_cast,我们将能够拥有它们(在其中包含正确的值)?!

2 个答案:

答案 0 :(得分:3)

如果指针确实指向Son对象(即动态类型Son,而静态类型是{{1然后,所有Father字段都存在,并且在转换指针后可以访问。

如果它没有指向Son,则转换将失败,给出空指针。

请注意Son仅在dynamic_cast具有多态性时才有效 - 也就是说,如果它声明至少一个虚函数。在您的示例中,它不是多态的,因此强制转换将失败。

答案 1 :(得分:1)

  

我们会失去儿子的领域/成员

不,你只是无法从指向Father的指针访问它。

  

通过做dynamic_cast,我们将能够拥有它们(正确的   里面的价值观)

是的,你会的,因为它仍然是Son对象(当然,如果传递的对象有Son类型的话。)

相关问题