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
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 to share