Naming Array Elements, or Struct And Array Within a Union

前端 未结 4 1838
梦毁少年i
梦毁少年i 2021-01-17 13:50

Consider the following struct:

struct Vector4D
{
   union
   {
      double components[4];
      struct { double x, y, z, t; } Endpoint;
   };
};
         


        
4条回答
  •  旧时难觅i
    2021-01-17 14:01

    You can circumvent any memory alignment issues by having references to each element of the array, as long as you declare the array before the references in the class to ensure they point to valid data. Having said that I doubt alignment would be an issue with doubles, but could be for other types (float on 64bit arch perhaps?)

    #include 
    using namespace std;
    
    struct Vector4D
    {
        Vector4D() : components(), x(components[0]), y(components[1]), z(components[2]), t(components[3]) { }
    
        double components[4];
    
        double& x;
        double& y;
        double& z;
        double& t;
    };
    
    int main()
    {
        Vector4D v;
    
        v.components[0] = 3.0;
        v.components[1] = 1.0;
        v.components[2] = 4.0;
        v.components[3] = 15.0;
    
        cout << v.x << endl;
        cout << v.y << endl;
        cout << v.z << endl;
        cout << v.t << endl;
    }
    

    Hope this helps.

提交回复
热议问题