Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 有条件地将基类引用参数作为派生类处理/强制转换并返回_C++_Oop_Inheritance_Casting_Reinterpret Cast - Fatal编程技术网

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
?我真的不明白。