继承、指针和软件体系结构

Inheritence, pointers and Software Architecture

本文关键字:软件体系结构 指针 继承      更新时间:2023-10-16
#include <iostream>
class EquationOfMotion
{
    public:
        // other attributes
        virtual void findNextTimeStep() = 0;
};
class SystemModel
{
    public:
        EquationOfMotion* p_eom;
        // other atributes 
        SystemModel(EquationOfMotion* new_p_eom)
        {
            p_eom = new_p_eom;
        }
};
class VehicleEquationOfMotion: public EquationOfMotion
{
    public: 
        VehicleEquationOfMotion(...){/* initialise attribute*/}
        virtual void findNextTimeStep(){}
};
class Vehicle: public SystemModel
{
 // ???? Implementation ?????
}

VehicleSystemModel的专门化,p_eom指向VehicleEquationOfMotion

我想初始化VehicleEquationOfMotion的实例,并在Vehicle中指向它的p_eom。我希望它只在Vehicle的范围内定义,同时不使用堆。是否有可能在不使用堆的情况下将VehicleEquationOfMotion对象驻留在Vehicle中?(如果没有,请建议设计哪里出了问题)。

可能有帮助:我考虑了这个问题中的实现,但遇到了麻烦(见问题)

如果我答对了你的问题,那么这样做:

  class FooChild : public FooParent
  {
  public:
      FooChild (int pX):m_BarChild(pX), FooParent(&m_BarChild) // point p_barPar to instance of BarChild (i.e. m_BarChild)
      {
      }
  private:
      BarChild m_BarChild; // instance of BarChild resided in the stack(not the heap) and is local to FooChild
  }

如果你想有FooParent。p_barPar要指向驻留在FooChild中的BarChild,您可能需要向FooParent添加默认变量和如下方法:set_p_barPar(BarChild* new_p_bar){p_barPar = new_p_bar;}。所以你得到:

class FooParent
{
    public:
        BarParent* p_barPar;
        FooParent (){}
        FooParent (BarChild* new_p_bar)
        {
            p_barPar = new_p_bar;
            std::cout << p_barPar->x << std::endl;
        }
    protected:
        set_p_barPar(BarChild* new_p_bar)
        {
            p_barPar = new_p_bar;
        }
}
然后你可以实现FooChild:
class FooChild : public FooParent
{
     public:
          FooChild(int new_x, BarChild* new_p_bar):_bar_child(new_x)
          {
               set_p_barPar(&_bar_child);
          }
     private:     //? Depends on your plans
         BarChild _bar_child();
}

使用类模板

class EquationOfMotion { ... };
template <typename EOM>
class SystemDynamics
{
    EOM EquationOfMotion;
    ...
};
class VehicleEquationOfMotion : public EquationOfMotion { ... };
class Vehicle : public SystemDynamics<VehicleEquationOfMotion> { ... };

也许这就是你想要的。但这种设计并不安全。你正在传递指针给一个未初始化的对象。

class Vehicle: public SystemModel
{
public:
    Vehicle(): SystemModel(&_vem)
    {
    }
    VehicleEquationOfMotion _vem;
}

但是,这样做更安全:

class SystemModel
{
    public:
        EquationOfMotion* p_eom;
        // other atributes 
        SystemModel()
        {
        }
};
class Vehicle: public SystemModel
{
   public:
   Vehicle(): SystemModel(&_vem)
   {
      p_eom = &_vem;
   }
   VehicleEquationOfMotion _vem;
};