Sometimes it is useful if you are able to access fields of a struct or class as an array.

For example, if you have the following struct:

struct Point3D {
    float x,y,z;
};

but you require to access the x,y and z-fields as an array, you can use an union:

union Point3D {
    float coord[3];
    struct {
        float x,y,z;
    };
};

Point3D p;
p.x = 1;
p.coord[1] = 2; // the same as  p.y = 2;
p.z = 3;

Another possibility is to create a class and overload the []-operator:

class Point3D {
public:
    float& operator[](int x) { 
        assert(x <= 2 && x >= 0); 
        if (x == 0) return this->x; 
        if (x == 1) return this->y; 
        return this->z;
    }

    float x,y,z;
};

Point3D p;
p.x = 1;
p[1] = 2;
p.z = 3;
  1. Reg (2011-02-28 00:58)

    I don’t like these ifs in the operator[] :) The operator[] itself is nice, but there is another way – the one that is used in D3DX in structs like D3DXVECTOR3:operator float * () { return &x; }operator const float * () const { return &x; }

  2. joe (2011-02-28 06:38)

    wow, very nice one. thank you for the tip. i love it :-)

  3. Br (2011-03-07 04:47)

    # float& operator[](int i) { # assert(i = 0); # return (&x)[i]; # }

Add your comment now