我可以将引用传递给映射,其中数据是指向派生类的指针吗?

Can I pass a reference to a map where the data is a pointer to a derived class?

本文关键字:派生 指针 数据 引用 映射 我可以      更新时间:2023-10-16

我想知道是否有可能将引用传递到映射,其中数据是指向派生类的指针?

  #include <map>
  class B {
  public:
  private:
    int x_;
  };
  class D : public B {
  public:
  private:
    int y_;
  };
  typedef std::map<int, B*> mapB_t;
  typedef std::map<int, D*> mapD_t;
  void foo(mapB_t& inmap) {
    ;
  }
  int main() {
    mapB_t mapB;
    mapD_t mapD;
    mapB[0] = new B;
    mapD[0] = new D;
    foo(mapB);
    foo(mapD);
    return 0;
  }

我收到这个编译错误:

。在函数'int main()'中:q.cc:34:错误:从"mapD_t"类型表达式初始化"mapB_t&"类型引用无效q.cc:22:错误:传递'void foo(mapB_t&)'的参数1

我认为解释应该是,尽管多态性允许将D类型对象传递给B&类型引用,但mapB_tmapD_t没有继承关系。因此mapB_t&不接受mapD_t。在您的情况下,使用多态性的正确方法可能是创建许多BD类型的对象,但始终将映射定义为mapB_t类型。B*类型指针既可以指向B,也可以指向D。您需要在B类中定义至少一个virtual函数,以允许函数foo判断由B*指针指向的对象是B还是D。下面是代码:

  class B{
    private:
      int x_;
    public:
      virtual ~B(){}     // Only for telling the identity of an object
  };
  class D: public B{
    private:
      int y_;            // Virtual destructor gets automatically inherited
  };

则函数foo可以使用dynamic_cast判断映射找到的对象类型是B还是D。下面是代码:

  void foo(std::map<int,B*> inmap){
     std::map<int,B*>::iterator it=inmap.find([Something]);
     D *pd=dynamic_cast<D*>(it->second);
     if(pd!=nullptr){
        // You know it->second is pointing to an object of type D
     }
     else{
        // Just an ordinary type B
     }
  }

如果您能做这个问题,您将对多态性有更好的理解:https://www.hackerrank.com/challenges/magic-spells