【问题标题】:Struct Inheritance Hierarchy - Dynamic down-cast结构继承层次结构 - 动态向下转换
【发布时间】:2013-06-24 17:33:20
【问题描述】:

我有以下 2 个结构,它们定义在一个模板类和一个包含基类元素的容器中,如下所示:

class template<typename T1, typename T2>
class TTestDataObject
{
private:
//base element
struct SDataContainerElement
  {
    T1* m_sData;
  };
//derived element
struct SInvalidDataContainerElement : SDataContainerElement
  {
    int m_eExpectedErrorCode;
  };

//container holding base elements
typedef std::map<T2, SDataContainerElement* > TDataContainer;

TDataContainer sCInvalidData;

public:
typedef TDataContainer::const_iterator TDataConstIterator;
}

我想实现一个方法,它可以从这个容器中提取信息,根据它拥有的元素,基类(SDataContainerElement)或派生类(SInvalidDataContainerElement)做不同的事情,我实现它如下:

template<typename TDataStruct, typename TDataEnum>
int TTestDataObject<T1, T2>::eGetExpectedError(T2 eIndex)
{

  TDataConstIterator sElement = sCInvalidData.find(eIndex);

 if(dynamic_cast<SInvalidDataContainerElement*>((sElement->second)) == NULL)
   return -1;
 else    
   return static_cast<int>(sElement->second->m_eExpectedError);
}

尝试编译会导致以下错误:

E2307 Type'TTestDataObject<BEREICHTYP,eTestDataBereichTyp>::SDataContainerElement' is not a defined class with virtual functions

我不明白这一点。任何人都可以向我解释这个错误并告诉我一个解决方案吗?

提前致谢!

【问题讨论】:

  • 您可能需要完全限定类型:TTestDataObject&lt;TDataStruct, TDataEnum&gt;::SInvalidDataContainerElement
  • dynamic_cast::SInvalidDataContainerElement*>
  • 能否请您给我们一个没有 eOpTyp、eIsaStoreErrorTyp 等的最小可重复示例。找到解决方案可能会有所帮助。
  • 感谢@StuartGolodetz,这解决了我的问题!

标签: c++ templates inheritance struct


【解决方案1】:

FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method? 中所述,我需要在基类中使用虚拟方法,例如虚拟析构函数。

为了使这段代码正常工作,我只是添加了

virtual ~SDataContainerElement(){};

到基础 - 结构。谢谢!

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多