我们正在为多态的本机代码编写c ++ / cli包装器,并希望尽可能地将多态性扩展到非本机端。到目前为止,给定一个c ++ / cli类实例,很容易检索底层本机类,但是在尝试确定哪个c ++ / cli包装器用于给定的本机类实例时会遇到麻烦。能够在这里避免使用switch语句会很好,但是如何?是否有更优雅的面向对象解决方案?
请注意,在以下代码中,我使用M的前缀作为C ++ / CLI类型(例如,FresnelScatterer是本机类,而MFresnelScatterer是C ++ / CLI包装类)。
本机c ++基类和继承类:
class Scatterer
{
public:
ScatterType Type;
Scatterer() {}
virtual ~Scatterer() {}
ScatterType GetType() { return Type; }
// Some virtual functions here...
};
class FresnelScatterer : public Scatterer
{
public:
// virtual function overrides
};
c ++ / cli基类和继承类:
public ref class MScatterer abstract
{
public:
Scatterer* m_Scatterer;
MScatterer() {}
MScatterer(MScatterer% mscatter)
{
m_Scatterer = mscatter.m_Scatterer;
}
MScatterer(Scatterer* scatter)
{
m_Scatterer = scatter;
}
[XmlElement("The_Scatterer_Type")]
int ScattererType;
virtual void initializeXMLdata()
{
ScattererType = (int) m_Scatterer->GetType();
}
virtual Scatterer* convertXMLdata() = 0;
~MScatterer() { }
// more wrapping here
};
public ref class MFresnelScatterer : MScatterer
{
public:
MFresnelScatterer() : MScatterer() {}
MFresnelScatterer(MFresnelScatterer% mfscatter) : MScatterer(mfscatter)
{
};
MFresnelScatterer(FresnelScatterer* mfscatter) : MScatterer(mfscatter)
{
};
virtual void initializeXMLdata() override
{
MScatterer::initializeXMLdata();
// other init
}
virtual Scatterer* convertXMLdata() override
{
//Scatterer
FresnelScatterer* sca = new FresnelScatterer();
return sca;
}
};
从C ++ / CLI开始的示例 - >原生C ++很好用,就在这里:
for each ( MScatterer^ mScatterer in readScene->ScattererList)
{
m_Scene->scattererList.push_back(mScatterer->convertXMLdata());
}
但是从本机c ++开始,我看不出如何教C ++ / CLI我的本机对象的类型没有使用switch语句:
for (uint i=0; i<m_Scene->scattererList.size(); i++)
{
switch (m_Scene->scattererList[i]->GetType())
{
case SCA_FRESNEL:
{
MFresnelScatterer^ sca = gcnew MFresnelScatterer((FresnelScatterer*) m_Scene->scattererList[i]);
sca->initializeXMLdata();
ScattererList->Add(sca);
break;
}
// other cases follow...
}
}
答案 0 :(得分:-1)
您可以在CreateObject
中编写虚拟方法MScatterer
,并在派生类中实现它。重写的CreateObject
将创建目标类的实例。没有必要使用GetType
方法。