0
#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 ?????
}

VehicleSystemModelwhere がp_eomを指す特殊化ですVehicleEquationOfMotion

のインスタンスを初期化し、 でそれをVehicleEquationOfMotion指すようにしたいと思います。のスコープ内でのみ定義し、同時にヒープを使用しないようにしたい。ヒープを使用せずにオブジェクトを内部に存在させることさえ可能ですか? (そうでない場合は、設計のどこが間違っているかを教えてください)。p_eomVehicleVehicleVehicleEquationOfMotionVehicle

役立つかもしれません:この質問の実装について考えましたが問題が発生しました (質問を参照)。

4

4 に答える 4

1

あなたの質問が正しく理解できた場合は、次のようにします。

  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
  }
于 2013-04-01T13:31:13.507 に答える
0

これはあなたが望むものかもしれません。しかし、設計は安全ではありません。初期化されていないオブジェクトにポインターを渡しています。

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;
};
于 2013-04-01T15:35:56.177 に答える
0

FooParent.p_barPar が FooChild 内に存在する BarChild を指すようにしたい場合は、デフォルトの ctor を 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();
}
于 2013-04-01T13:22:22.513 に答える