簡體   English   中英

dynamic_cast拋出std :: bad_cast異常

[英]std::bad_cast exception thrown by dynamic_cast

在下面的代碼,我得到std::bad_cast鑄造時拋出的異常derived.properties_BasePropertiesDerivedProperties 查看代碼,在我看來,在Base類構造函數中引用DerivedProperties初始化BaseProperties ,出現了DerivedProperties

我想要實現的是一個簡單的UI,其中Base本質上是我的Component接口, Derived是任何被認為是Component的東西。 似乎可以公平地假設組件可能具有不同的屬性,但具有一些相似的屬性,例如大小和位置。

誰能提供有關如何最好地實現我的目標的建議?

#include <iostream>
#include <string>

// Properties for all objects of Base type
class BaseProperties {
public:
  BaseProperties( std::string baseProperty ):
    baseProperty_( baseProperty ) { }

  virtual ~BaseProperties(  ) {  }
  std::string getBaseProperty(  ) { return baseProperty_; }

protected:
  std::string baseProperty_;
};

// Properties specific to objects of Derived type
class DerivedProperties: public BaseProperties {
public:
  DerivedProperties( std::string baseProperty, std::string derivedProperty ):
    BaseProperties( baseProperty ),
    derivedProperty_( derivedProperty ) {  }

  std::string getDerivedProperty(  ) { return derivedProperty_; }

private:
  std::string derivedProperty_;
};

class Base {
public:
  Base( BaseProperties& properties ):
    properties_( properties ) {  }

  virtual ~Base(  ) {  }

protected:
  BaseProperties& properties_;
};

class Derived : public Base {
public:
  Derived( DerivedProperties properties ):
    Base( properties ) {  }

  friend std::ostream & operator << ( std::ostream& out, const Derived& derived );
};

std::ostream & operator << ( std::ostream& out, const Derived& derived ) {  
  return out << derived.properties_.getBaseProperty(  ) << ", "
             << dynamic_cast< DerivedProperties& >( derived.properties_ ).getDerivedProperty(  );
}

int main(  ) {
  Derived derived( DerivedProperties( "BaseProperty", "DerivedProperty" ) );

  std::cout << derived << std::endl;
  return 0;
}

您的派生類應將DerivedProperty&作為參數,類似於您的基類如何做到這一點:

class Derived : public Base {
public:
  Derived( DerivedProperties& properties ):
    Base( properties ) {  }

  friend std::ostream & operator << ( std::ostream& out, const Derived& derived );
};

由於您不是將引用用作構造函數參數而是實際對象,因此實際上是在存儲對臨時對象的引用,一旦構造函數退出,該臨時對象將不再存在。

Derived構造函數結束時, properties參數將被銷毀。 但是,您已經存儲了對該對象的引用,因此該引用現在處於懸空狀態。 相反,您應該使properties_成員不是引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM