Home > OS >  Cpp predefined structs?
Cpp predefined structs?

Time:12-19

Last time I used C was when I attended university, therefor I am not very fluent in it.

I wanted to create a small game, and because I am used to C# I wanted to create predefinded struct objects.

Here is the C# code for reference:

public struct Vector2 : IEquatable<Vector2>
{

  private static readonly Vector2 _zeroVector = new Vector2(0.0f, 0.0f);
  private static readonly Vector2 _unitVector = new Vector2(1f, 1f);
  private static readonly Vector2 _unitXVector = new Vector2(1f, 0.0f);
  private static readonly Vector2 _unitYVector = new Vector2(0.0f, 1f);

  [DataMember]
  public float X;
  [DataMember]
  public float Y;

  public static Vector2 Zero => Vector2._zeroVector;
  public static Vector2 One => Vector2._unitVector;
  public static Vector2 UnitX => Vector2._unitXVector;
  public static Vector2 UnitY => Vector2._unitYVector;

  public Vector2(float x, float y)
  {
    this.X = x;
    this.Y = y;
  }
}

In C# I could now use this code to get a Vector with x = 0 and y = 0

var postion = Vector2.Zero;

Is there a way to create something like this in C or do I have to life with the basicness of c and use a struct like this?

struct Vector2 {
    float x, y;
    Vector2(float x, float y) {
        this->x = x;
        this->y = y;
    }
};

CodePudding user response:

I might have a solution but I am not sure.

Vector2.h

struct Vector2 {
    static const Vector2 Zero;
    static const Vector2 One;
    float x {}, y {};
}

Vector2.cpp

#include "Vector2.h"

const Vector2 Vector2::Zero = Vector2 {0, 0};
const Vector2 Vector2::One = Vector2 {1, 1};

CodePudding user response:

First off, with recent versions of C , you can simplify your struct definition like this:

struct Vector2 {
    float x{}, y{};
};

This guarantees that x and y are initialized with 0, you don't need the separate constructor as you show it. You can then use the struct like this:

Vector2 myVec;  // .x and .y are set to 0
myVec.x = 1; myVec.y = 2;

You can even use what's called an "initializer list" to create a struct with predefined values for x and y instead of the default 0, like this:

Vector2 myVec2{1,2};

Regarding your need for a "global" instance of your Vector2 struct, you can make use of the static keyword in C similarly as in C#:

struct Vector2 {
    float x{}, y{};
    static const Vector2 Zero;
};

In contrast to C , you cannot specify the value of constant directly in the class though (if you try you get an incomplete type error, since at the time when the compiler encounters the constant, the class definition is not complete yet); you need to "define" the constant somewhere outside your class:

const Vector2 Vector2::Zero{};

While the above struct Vector2 ... typically goes somewhere in a .h file to be included by multiple other files, the definition should go into a .cpp file, and not in the header, otherwise you will get multiply defined symbol errors.

  • Related