代码之家  ›  专栏  ›  技术社区  ›  Thomas Matthews

动态转换与多重继承

  •  1
  • Thomas Matthews  · 技术社区  · 14 年前

    这个 dynamic_cast

    层次结构:

    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)中返回0,如何解决此问题?

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

    1 回复  |  直到 14 年前
        1
  •  2
  •   sth ACP    14 年前

    注意:为了简单起见,我在这个例子中使用基本指针。实际代码使用 boost::shared_ptr .

    这就是你的问题:你不能 dynamic_cast shared_ptr<A> shared_ptr<B> 因为这两种类型实际上并不相关,即使 A B 是。

    幸运的是在你的问题中 动态播放 应该没必要,因为 Record_ID_As_Field* 应隐式转换为 Field_Interface* (因为一个是从另一个派生出来的)。 shared_ptr 共享\u ptr 物体,所以 shared_ptr<Record_ID_As_Field> 应隐式转换为 shared_ptr<Field_Interface> .

    动态播放 ,应该有用。

    special constructor 提供单位

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

    (我不知道如果 动态播放