dynamic_cast抛出的std :: bad_cast异常

时间:2014-02-20 16:08:16

标签: c++ inheritance polymorphism c++03

在下面的代码中,从std::bad_castderived.properties_投射BaseProperties时,我遇到了DerivedProperties异常。看一下这段代码,我觉得在BaseProperties初始化DerivedProperties时,Base类构造函数中的Base会出错。

我想要实现的是一个简单的用户界面,其中Derived本质上是我的组件界面,#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; } 是任何被视为组件的东西。看起来公平的假设是,组件可能具有不同的属性,但具有一些类似的属性,例如大小和位置。

任何人都可以就如何最好地实现我的目标提出任何建议吗?

{{1}}

2 个答案:

答案 0 :(得分:2)

派生类应该使用DerivedProperty&作为参数,类似于Base类的参数:

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

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

由于您没有将引用作为构造函数参数而是实际对象,因此您实际上存储了对临时对象的引用,一旦构造函数退出,该引用就不再存在。

答案 1 :(得分:1)

Derived构造函数结束时,properties参数将被销毁。但是,您已经存储了对该对象的引用,因此引用现在处于悬空状态。相反,您应该使properties_成员不是参考。