我可以将引用传递给数据是指向派生类的指针的地图吗?

时间:2016-10-24 21:10:21

标签: 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*> 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;
  }

我收到此编译错误:

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

1 个答案:

答案 0 :(得分:1)

我认为解释应该是即使多态性允许将D类型对象传递给B&类型引用,mapB_tmapD_t也没有继承关系。因此mapB_t&不接受mapD_t。在您的情况下使用多态的正确方法可能是创建BD类型的许多对象,但始终将地图定义为mapB_t类型。 B*类型指针可以指向BD。您需要在类B中定义至少一个virtual函数,以允许函数foo判断B*指针指向的对象是否为{{1}或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判断地图找到的对象是B类型还是D类型。这是代码:

dynamic_cast

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