将具有条件的Ada记录转换为C++

hur*_*tch 3 c++ struct ada

我有一个任务,我需要将一些Ada代码转换为C++代码,使其尽可能与Ada代码相似.Ada代码如下

    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;
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用一个class但是根据问题的语言和老师的个性来判断我认为他正在寻找一个struct.我不清楚如何创建一个内部不同情况所需的逻辑struct.老师非常特别,所以我认为需要最小的内存占用.

我是CSc的学生,如果解决方案很简单,请原谅我.谢谢!

更新:所以最终答案比我想象的要简单.

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;
  };
 };
Run Code Online (Sandbox Code Playgroud)

像往常一样,我推翻了它.感谢您的输入!

per*_*eal 5

看起来你想从基类Shape类派生 Circle,Triangle和Rectangle.有一些常见属性(填充,颜色)需要进入基础Shape,派生类将具有直径或左右侧或其他附加属性.

另一种方法是enum {Circle, Rectangle, ..}在Shape 结构中使用type-id字段(),并为直径和其他类型相关成员保存不同的子结构.这看起来更像是示例(和C),但不像C++.

  • 我确实认为衍生的类也是预期的.但是,这也可以在Ada中完成,没有变体记录. (2认同)
  • Ada代码和C++等价物(使用简单的结构和联合)之间的主要区别在于后者不强制执行变体.在Ada中,如果`Obj.Form = Circle`,则引用`Obj.Left_Side`将引发`Constraint_Error`异常.在C++中,引用`Obj.u.Left_Side`只是访问结构的那一部分,静静地给你垃圾.(假设您不使用继承.) (2认同)