【问题标题】:Dynamic cast and multiple inheritance动态转换和多重继承
【发布时间】:2010-08-20 18:15:00
【问题描述】:

dynamic_cast 运算符在我应用到指向多重继承对象实例的指针时返回零 (0)。我不明白为什么。

层次结构:

class Field_Interface
{
  public:
    virtual const std::string get_field_name(void) const = 0; // Just to make the class abstract.
};


class Record_ID_Interface
{
  public:
    virtual bool has_valid_id(void) const = 0;
};


class Record_ID_As_Field
: public Field_Interface,
  public Record_ID_Interface
{
// This class behaves as a Field and a Record_ID.
// ...
}


// A demonstration function
void Print_Field_Name(const Field_Interface * p_field)
{
  if (p_field)
  {
    cout << p_field->get_field_name() << endl;
  }
  return;
}


// A main function for demonstration
int main(void)
{
  Record_ID_As_Field *  p_record_id = 0;
  p_record_id = new Record_ID_As_Field;
  if (p_record_id)
  {
     // (1) This is the trouble line
     Print_Field_Name(dynamic_cast<Field_Interface *>(p_record_id));
  }
  return 0;
}

我想让Record_ID_As_Field 被视为Field_Interface,但也适合需要Record_ID_Interface 的地方。

为什么上面(1)中的dynamic_cast返回0,我该如何解决?

我在 Windows XP 上使用 Visual Studion 2008。

注意:为简单起见,我在此示例中使用基本指针。实际代码使用boost::shared_ptr

【问题讨论】:

  • 没有理由测试p_record_id 不为空,new 永远不会返回空值。 (我假设这是因为它是一个 sn-p,但请确保您的公共基类具有虚拟析构函数。)
  • 我一直认为动态转换是为了向上转换......并且向下转换是隐式的......
  • 没有证据表明您实现了抽象方法。你有吗?
  • @Vardhan:向上转换(从派生到基)是自动的,向下转换(从基到派生)需要显式转换。
  • 哦,您的代码是正确的,dynamic_cast 不应该返回 0。您在从实际问题到问题问题的过程中“修复”了问题。

标签: c++ pointers multiple-inheritance dynamic-cast


【解决方案1】:

注意:为简单起见,我在此示例中使用基本指针。实际代码使用boost::shared_ptr

这就是你的问题:你不能 dynamic_castshared_ptr&lt;A&gt;shared_ptr&lt;B&gt;,因为这两种类型实际上并不相关,即使 AB 是。

幸运的是,在您问题的特定情况下,dynamic_cast 不是必需的,因为Record_ID_As_Field* 应该可以隐式转换为Field_Interface*(因为一个派生自另一个)。 shared_ptr 实现转换运算符,将这些隐式转换提升到相应的shared_ptr 对象,因此shared_ptr&lt;Record_ID_As_Field&gt; 应该可以隐式转换为shared_ptr&lt;Field_Interface&gt;

如果你省略了dynamic_cast,它应该可以工作。

如果您确实需要进行动态转换,您可以使用shared_ptr 提供的special constructor

shared_ptr<Record_ID_As_Field> raf;
shared_ptr<Field_Interface> fi(raf, dynamic_cast<FieldInterface*>(raf.get());

(我不确定如果dynamic_cast 失败会发生什么,所以您应该调查处理这种情况的最佳方法。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多