I'm making a simple class for Vector3D type objects. The following code will compile and run perfectly.
class Vector3D {
float x, y, z;
public:
Vector3D() = default;
Vector3D(float a, float b, float c) : x(a), y(b), z(c) {};
float& operator [](int i) {
return (&x)[i];
}
const float& operator [](int i) const {
return (&x)[i];
}
}
int main(int argc, char ** argv){
Vector3D myVec(1,2,3);
printf("Value of y: %d\n", myVec[1]);
}
However when I remove the address-of operator (&) I get an error and the code will not work. Why is the (&) necessary? ie:
return (x)[i]; // will not compile "expression must have pointer-to-object type"
return (&x)[i]; // all good here
Also I'm having trouble understanding how this even works. How is it that the function can return the ith float, do member variables get stored in a contiguous way in memory (like arrays)?
The way you're doing this is so tricky, and this is undefined behavior .
There is no guarantee for struct member layout, but most time the members are placed on memory as:
x---y---z--- (4 bytes each)
x[0]
x[1]
x[2]
So this is why your code is working (remember this is not a defined behavior).
Your code doesn't do bounds checking anyway, so consider:
float x[3]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.