Base Class reference to Pointer of Derived Class

大憨熊 提交于 2021-01-29 20:53:14

问题


I would like to have, in a base class A, a reference (or pointer if not possible) to a pointer in a derived class. This would look like this :

 BaseClassController
        {
          public :
            //Constructors, destructor,...

          protected :
            BaseDataClass *& m_current;
        }

DerivedClassAController : public BaseClassController
    {
      public :
        //Constructors, destructor,...

      protected :
        DerivedDataClassA * m_currentA;
    }

DerivedClassBController : public BaseClassController
    {
      public :
        //Constructors, destructor,...

      protected :
        DerivedDataClassB * m_currentB;
    }

with the Data classes being :

BaseDataClass
{
    void doSomething();
}

DerivedDataClassA : public BaseDataClass
{
 //...
}

DerivedDataClassB : public BaseDataClass
{
 //...
}

What I would like to do next in BaseClassController is :

BaseClassController::someFunction(){
    m_current->doSomething();
}

The problem is that the objects pointed by m_currentA and m_currentB will change a lot through the life of the program, and I would like the m_current reference to change automatically when the derived class pointer changes. Concretly, I would like the function changing the object pointed by m_currentA to look like this :

DerivedClassAController::changerCurrentA(DerivedDataClassA* ptA){
   m_currentA = ptA;
}

and not like this :

DerivedClassAController::changerCurrentA(DerivedDataClassA* ptA){
   m_currentA = ptA;
   m_current = ptA;
}

I tried by passing the pointer in the derived class constructor :

BaseClassController::BaseClassController(BaseDataClass* pt)
 : m_current(pt)
{
}

DerivedClassAController::DerivedClassAController()
 : BaseClassController(m_currentA),
   m_current(A)
{
}

But I ended up having a m_current pointing to a DerivedDataClassB in DerivedClassAController.

Is this acheivable ? Or is there a better way to do that ?

Note : DerivedClassAController will use m_currentA as a DerivedDataClassA 95% of the time. Using only the m_current pointer in the base class will end putting dynamic_cast(m_current) everywhere.


回答1:


I think that following approach would work: Instead of using a member reference, create a virtual function in BaseClassController that returns a copy of the pointer:

struct BaseClassController {
    virtual BaseDataClass* m_current() = 0;

And implement it differently in each derived controller:

BaseDataClass* DerivedDataClassA::m_current() {
    return m_currentA;


来源:https://stackoverflow.com/questions/38590949/base-class-reference-to-pointer-of-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!