我正在使用 Visual Studio 并执行有效的动态转换。RTTI 已启用。
编辑:更新代码更真实
struct base
{
virtual base* Clone()
{
base* ptr = new base;
CopyValuesTo( ptr );
return ptr;
}
virtual void CopyValuesTo( base* ptr )
{
...
}
virtual ~base()
{
}
}
struct derived : public base
{
virtual base* Clone()
{
derived* ptr = new derived;
CopyValuesTo( ptr );
return ptr;
}
virtual void CopyValuesTo( base* ptr )
{
...
}
virtual ~derived()
{
}
}
void Class1::UseNewSpec( base* in_ptr ) //part of a totally unrelated class
{
derived* ptr = dynamic_cast<derived *>(in_ptr);
if( !ptr )
return;
delete m_ptr;
m_ptr = ptr->Clone(); //m_ptr is a member of Class1 of type base*
}
//usage :
Class1 obj;
derived new_spec;
obj.UseNewSpec( &new_spec );
我的调试器说在抛出异常时 in_ptr 是正确的类型。谷歌似乎特别没有帮助。有任何想法吗?干杯。