C++ 我是否可以传递对映射的引用,其中数据是指向派生类的指针?

C++ 我是否可以传递对映射的引用,其中数据是指向派生类的指针?,c++,C++,我想知道是否可以传递对映射的引用,其中数据是指向派生类的指针 #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*> ma

我想知道是否可以传递对映射的引用,其中数据是指向派生类的指针

  #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;
  }
#包括
B类{
公众:
私人:
int x_2;;
};
D类:公共B类{
公众:
私人:
int y_;
};
typedef标准::地图地图;
typedef std::地图地图;
void foo(mapB_t&inmap){
;
}
int main(){
mapB_t mapB;
mapD_t mapD;
mapB[0]=新的B;
mapD[0]=新的D;
foo(mapB);
foo(mapD);
返回0;
}
我收到以下编译器错误:

q、 cc:在函数“int main()”中: q、 cc:34:错误:从“mapD\u t”类型的表达式初始化“mapB\u t&”类型的引用无效
q、 cc:22:错误:在传递'void foo(mapB_t&')的参数1时,

我认为解释应该是,即使多态性允许将
D
类型对象传递给
B&
类型引用,
mapB_t
mapD_t
没有继承关系。因此
mapB\u t&
不接受
mapD\u t
。在您的情况下使用多态性的正确方法可能是创建许多
B
D
类型的对象,但始终将映射定义为
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
  };
  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
     }
  }
然后,函数
foo
可以使用
dynamic\u cast
判断地图找到的对象是
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
  };
  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
     }
  }
void foo(标准::映射inmap){
std::map::iterator it=inmap.find([Something]);
D*pd=动态施法(它->秒);
如果(pd!=空PTR){
//你知道->第二个指向一个类型为D的对象
}
否则{
//只是普通的B型
}
}

如果你能解决这个问题,你就会更好地理解多态性:

编译器错误很好地表明你不能这么做。我认为应该解释一下,即使多态性允许你将
D
类型对象传递给
B&
类型引用,
mapB\u t
mapD\u t
没有继承关系。因此,<代码> MMABGTT和不接受<代码> MAPdtt < /COD>。考虑会发生什么:<代码> IMAP(0)=新B;
将是一场灾难。在您的情况下使用多态性的正确方法应该是创建许多
B
D
类型的对象,但始终将映射定义为
mapB\t
类型。
B*
类型指针可以指向
B
D