C++ 有条件地将基类引用参数作为派生类处理/强制转换并返回
我有一个函数,它的签名或调用者我不能轻易更改,它获取对结构的引用。此结构属于基类,但取决于此函数中发现的内容,此结构被确定为继承类型并进行相应操作。稍后,根据我们在此处的设置方式,这些数据将根据需要进行动态转换C++ 有条件地将基类引用参数作为派生类处理/强制转换并返回,c++,oop,inheritance,casting,reinterpret-cast,C++,Oop,Inheritance,Casting,Reinterpret Cast,我有一个函数,它的签名或调用者我不能轻易更改,它获取对结构的引用。此结构属于基类,但取决于此函数中发现的内容,此结构被确定为继承类型并进行相应操作。稍后,根据我们在此处的设置方式,这些数据将根据需要进行动态转换 struct Base { int baseMember; } struct Derived : public Base { int derivedMember; } enum EvtType { EVT_A, EVT_B } void handle
struct Base {
int baseMember;
}
struct Derived : public Base {
int derivedMember;
}
enum EvtType {
EVT_A,
EVT_B
}
void handleEvent(Base& data) {
data.baseMember++; //adjust the common member
switch (getEventType()) // some static returning EvtType
{
case EVT_A:
// I can instatiate this as required, setting baseMember in a constructor
// or something
Derived derivedInst;
// and now i can set the derived members as needed
derivedInst.derivedMember += 56; // this is just what happens with EVT_As
// FIXME: but how do I get this object into the data parameter?
break;
case EVT_B:
// do it differently, but the same idea
break;
}
//handle other event types
}
即使传入引用的对象可能已经被其他人分配为基
,通过类似于reinterpret\u cast
的方式也可以这样做吗
另外,考虑到我不能扩展
派生的
或基本的
类,根据开关中案例的内容,是否有更整洁的方法来设置从EvtType
到设置正确的派生类的映射。据我所知,您实际上需要找出数据的真实类型。因此,您可以通过typeid
操作符来检查它。看见希望这有帮助。所以你基本上是在问,如何说data=derivedInst代码>?我认为这是不可能的,除非基类使用类型擦除。为什么不能执行静态转换(数据)。derivedMember+=56
?我真的不明白。