A Struct property that returns a structure of its type

I am trying to define a structure in C ++ that has properties to return predefined values ​​of its own type.

Like many APIs, for vectors and colors, for example:

Vector.Zero; // Returns a vector with values 0, 0, 0
Color.White; // Returns a Color with values 1, 1, 1, 1 (on scale from 0 to 1)
Vector.Up; // Returns a vector with values 0, 1 , 0 (Y up)

      

Source: http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx (MSDN page their colors)

I tried to find the watch, but I can't figure out what he named.

+3


source to share


3 answers


You can simulate it with static elements:



struct Color {
    float r, g, b;
    Foo(float v_r, float v_g, float v_b):
        r(v_r), g(v_g), b(v_b){};
    static const Color White;
};

const Color Color::White(1.0f, 1.0f, 1.0f);

// In your own code
Color theColor = Color::White;

      

+2


source


//in h file
struct Vector {
 int x,y,z;

 static const Vector Zero; 
};

// in cpp file
const Vector Vector::Zero = {0,0,0};

      



Like this?

+4


source


This is a static property. Unfortunately C ++ doesn't have properties of any type. To implement this, you probably want either a static method or a static variable. I would recommend the first one.

For example, Vector

you need something like:

struct Vector {
  int _x;
  int _y;
  int _z;

  Vector(int x, int y, int z) {
    _x = x;
    _y = y;
    _z = z;
  }

  static Vector Zero() {
    return Vector(0,0,0);
  }
}

      

Then you have to write Vector::Zero()

to get the null vector.

+2


source







All Articles