繁体   English   中英

dynamic_cast返回std :: bad_cast,我不知道为什么

[英]dynamic_cast returns std::bad_cast and I don't know why

我有一个基类和一个派生类,并且如果基是基类的对象,则有一行代码会给我错误std :: bad_cast。 为什么会给我这个错误? 尝试一下,我已经看到static_cast起作用了,但是我不知道为什么。

该行是:

#include <iostream>
  class Base
  {
   public:
     virtual void g(){std::cout<<"a";};
   };

  class Derived: public Base
 {
  public:
   void g(){std::cout<<"b";};
  };

  void fn(Base & base) 
  { 

    Derived & pb = dynamic_cast<Derived &>(base); 

     pb.g(); 

   } 

  int main() 
   { 
     Base f1;
    fn(f1);
   } 

您正在尝试将Base&实际上是Base& (不是Derived& )转换为Derived&因此当然会失败。 请记住,所有Derived对象也是Base对象,但并非所有Base对象都是Derived对象。

您可能想要做的是将实际的Derived对象传递给函数

int main()
{
    Derived f1;
    fn(f1);
}

让我用一个更具体的例子来解释。

struct Rectangle
{
    Rectangle(int width, int height):
        width(width), height(height) {}
    virtual ~Rectangle() {}
    int width, height;
};
struct Square: Rectangle
{
    Square(int size): Rectangle(size, size) {}
};

int main()
{
    Square square(3);
    Rectangle rect(1, 2);

    Rectangle& ref_to_square = square;
    Rectangle& ref_to_rect   = rect;

    // This is okay
    // ref_to_square is a reference to an actual square
    dynamic_cast<Square&>(ref_to_square);

    // This will fail
    // ref_to_rect is *not* a reference to an actual square
    dynamic_cast<Square&>(ref_to_rect);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM