gpt4 book ai didi

c++ - dynamic_cast 抛出的 std::bad_cast 异常

转载 作者:行者123 更新时间:2023-11-28 00:33:26 28 4
gpt4 key购买 nike

在下面的代码中,在将 derived.properties_BaseProperties 转换为 DerivedProperties 时,我得到了一个 std::bad_cast 异常抛出。查看代码,在我看来,在 Base 类构造函数中引用 DerivedProperties 初始化 BaseProperties 时出现问题.

我想要实现的是一个简单的 UI,其中 Base 本质上是我的组件接口(interface),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;
}

最佳答案

您的派生类应将 DerivedProperty& 作为参数,类似于您的基类的做法:

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

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

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

关于c++ - dynamic_cast 抛出的 std::bad_cast 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21913273/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com