سؤال

I have a question to inherited variables. Parts of my sourcecode:

class Piston{           //abstract class        
   ...                  //virtual functions        
};

class RectangularPiston: public Piston
{
  ...                   //non virtual implementation of the Piston functions
  bool setGridSize(...) //this function doesn't exists in the Piston class
  {
    ...
  }
}

class Transducer{       //abstract class
    ...                 //virtual functions
  protected:
    Piston *m_piston;
};

class RectilinearTransducer: public Transducer
{
    ... //non virtual implementation of the Piston functions
    bool setGridSizeOfPiston(...)
    {
        return m_piston->setGridSize(...);  //doesn't work
    }

}

RectilinearTransducer holds a m_piston, which is always a RectlinearPiston! But m_piston is inherited by the Transducer class and I can't use the setGridSize()-function.

error message: error C2039: 'setGridSize': Is no element of 'Piston'

The function setGridSize doesn't exists in the Piston class...

How can I solve this Problem? Should I overwrite the m_piston variable like I can do it with virtual functions? The m_piston variable exists as Piston* m_piston, because I inherited it by the Transducer class.

Thanks for help

هل كانت مفيدة؟

المحلول 2

If you can't make setGridSize a virtual function in the parent then you might want to add a function that simply casts m_piston to RectangularPiston* then call this function when your class needs to refer to m_piston.

RectangularPiston* getRecPiston() {
    return static_cast<RectangularPiston*>(m_piston);
}

bool setGridSizeOfPiston(...) {
        return getRecPiston()->setGridSize(...)        
}

نصائح أخرى

You need to make setGridSize a virtual function of Piston (either pure virtual or otherwise).

e.g

class Piston {
  protected: (or public)
     virutal bool setGridSize(..) = 0;
...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top