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

时间:2018-11-10 00:59:16

标签: c++ dynamic-cast

我有一个基类和一个派生类,并且如果基是基类的对象,则有一行代码会给我错误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);
   } 

1 个答案:

答案 0 :(得分:4)

您正在尝试将实际上是let jsonResponse = """ { "abilities": [ { "ability": { "name": "chlorophyll", "url": "https://pokeapi.co/api/v2/ability/34/" }, "is_hidden": true, "slot": 3 }, { "ability": { "name": "overgrow", "url": "https://pokeapi.co/api/v2/ability/65/" }, "is_hidden": false, "slot": 1 } ], "name": "SomeRandomName" } """ struct Pokemon: Codable { let abilities: [AbilityElement] let name: String struct AbilityElement: Codable { let ability: Ability let isHidden: Bool let slot: Int struct Ability: Codable { let name: String let url: String } } } var pokemon: Pokemon? do { let jsonDecoder = JSONDecoder() jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase if let data = jsonResponse.data(using: .utf8) { pokemon = try jsonDecoder.decode(Pokemon.self, from: data) } } catch { print("Something went horribly wrong:", error.localizedDescription) } print(pokemon) (而不是Base&)的Base&投射到Derived&,因此当然会失败。请记住,所有Derived&对象也是Derived对象,但并非所有Base对象都是Base对象。

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

Derived

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

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