c++ class returning pointer to member to be used as array -



c++ class returning pointer to member to be used as array -

class vector3 { private: float x; float y; float z; public: vector3( float x, float y, float z ) : x(x), y(y), z(z) {} // returning pointer first fellow member utilize array. // assumes info layout sizeof(float) sizeof(float) sizeof(float) // , order not changed. float* ptr() { homecoming &x; } // implicit casting version of ptr() operator float*() { homecoming ptr(); } }; ... vector3 v(1,2,3); float x = v[0]; float y = v[1]; float z = v[2];

will valid on platform , compiler setting? found working under visual studio 2013 correctly, i'm having feeling quite horribly wrong.

your feeling correct.

but what's point? why don't have array fellow member rather 3 individual float members?

class vector3 { private: std::array<float, 3> data; public: vector3( float x, float y, float z ) : data( {x, y, z } ) {} float* ptr() { homecoming data.data(); } operator float*() { homecoming ptr(); } };

this uses c++11, can accomplish same thing c++03:

class vector3 { private: float data[3]; public: vector3( float x, float y, float z ) { data[0] = x; data[1] = y; data[2] = z; } float* ptr() { homecoming data; } operator float*() { homecoming ptr(); } };

and of course, biggest question is: why don't utilize std::vector or std::array directly? class seems reinvent wheel.

c++

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -