lundi 3 juin 2019

Convert between child objects when using polymorphism?

I've got a problem that probably has to do with my design, but I'd like suggestions on how to improve it. Essentially I have a parent class which has several child classes and I need to be able to convert between the child classes. However, the object to be converted in my current design uses polymorphism and a Parent class pointer. I do this because in the end which child class is used is determined by user input. I have figured out three ways to solve this problem: 1. Implement a separate "converter" class that can take each child class and convert it to another child class. 2. Declare virtual functions that converts each child class into other child classes. (This would create circular dependencies, which I don't think are a good idea...) 3. Include an enum data member in the objects that say which type they are so I can use a switch() statement when converting.

Are there other ways I should be thinking about it? Here is some code that I think shows what I want to do.

class Rotation
{
   public:
      void  Set();
      Vector Get();
      virtual void Rotate(float amount);
      virtual void SetFromQuaternion(Vector t_quaternion);
   private:
      Vector m_rotation;
}

class EulerAngles : Rotation
{
   public:
     void Rotate(float t_amount);
     void SetFromQuaternion(Vector t_quaternion);
}

class Quaternion: Rotation
{ 
  public:
     void Rotate(float t_amount);
     void SetFromQuaternion(Vector t_quaternion);//Just copies data
}
class RigidBody
{
  public:
     RigidBody(Rotation *t_rotation);
     Rotation GetRotation();
     void SetRotationFromQuaternion(Vector t_rotation) {m_rotation->SetRotationFromQuaternion(t_rotation);}
  private:
     std::unique_ptr<Rotation> *m_rotation;
}
int main()
{
   //Argument is based on user input file, but euler angles are used as an example
   Rigidbody body_1 = RigidBody(new EulerAngles());
   // I want to rotate using quaternions to avoid singularities, but then convert back to euler angles. So here's where I would convert. How should I do this?
   Quaternion temp_quaternion = (Quaternion)body_1.GetRotation();
   temp_quaternion.Rotate(amount);
   body_1.SetRotationFromQuaternion(temp_quaternion.Get());

   return;
}

Please note that my actual code is more complicated. My question is more to do with overall design "best practices." Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire