Quote:Original post by Alpha_ProgDes
I didn't create that code. As I said, it was from another thread. The title is "... in C++". Could someone show how that
float &operator[]( int i ) const { return ( float & )*( &x + i ); }
code is supposed to work in actual code?
Ok, basically x, y, and z are declared in that order right next to each other, so they should be adjacent in memory.
So if you obtain a pointer to x (&x) and then you add an integer to that pointer (i.e. &x + 1) you will end up with the address of the data at sizeof(x) bytes times the integer past x.
So (&x + 0) is the address of x, (&x + 1) is the address of y, etc. (note however that (&x + 3) would point somewhere bad, so it would be a good idea to assert(i >= 0 && i < 3) )
Then we de-reference the pointer (i.e. *(&x + 1) ) to get the value pointed to, and we return a reference to it.