Translate Ada entry with conditional to C ++

I have an assignment where I need to translate my Ada code to C ++ code, making it as similar as possible to Ada code. Ada code looks like this

    type Shape is (Circle, Triangle, Rectangle);
    type Colors is (Red, Green, Blue);
    type Figure(Form: Shape := Circle) is
        record
            Filled: Boolean;
            Color: Colors;
            case Form is 
                when Circle =>
                    Diameter: Float;
                when Triangle =>
                    Left_Side: Integer;
                    Right_Side: Integer;
                    Angle: Float;
                when Rectangle =>
                    Side_1: Integer;
                    Side_2: Integer;
            end case;
        end record;

      

I know I can use class

, but judging by the language of the question and the personality of the teacher, I guess what he is looking for struct

. I just don't understand how to create the logic required for different cases internally struct

. The teacher is very specific, so I guess the minimum amount of memory is required.

I am a CSc student, forgive me if the solution is simple. Thank!

Update: So the final answer was simpler than I thought.

enum Shape {Circle, Triangle, Rectangle};
enum Colors {Red, Green, Blue};
struct Figure {
  bool Filled;
  Colors Color;
  Shape Form;
  union {
    float Diameter;
    struct {
      int Left_Side;
      int Right_Side;
      float Angle;
    } tri;
    struct {
      int Side_1;
      int Side_2;
    } rect;
  };
 };

      

As usual, I changed my mind. Thanks for all your data!

+3


source to share


2 answers


It seems that you intend to bring classes Circle, Triangle and Rectangle base class Shape. There are general properties (filled, colored) that need to fit into your base shape, and derived classes will have diameter, or left-hand sides, or other additional properties.



An alternative would be to have a type-type field ( enum {Circle, Rectangle, ..}

) in the Shape struct and a union field containing different substructures for diameter and other type-dependent items. It will look more like the example (and C), but less like C ++.

+5


source


For a non-class answer:



  • Make enumerations for shape and color types.
  • Make the struct

    data Circle, Triangle, and Rectangle.
  • Make a shape struct

    containing a filled box, a colored box, and a box that is union

    struct

    made in # 2.
  • [optional] Create "constructors" for the various shapes that return struct

    from # 3, initialized correctly.
+1


source







All Articles