How to access anonymous union / struct member in C ++?

This question is my mistake. . The code described below is well built without problems.


I have this class.

vector.h

struct Vector { union { float elements[4]; struct { float x; float y; float z; float w; }; }; float length(); } 

Vector.cpp

 float Vector::length() { return x; // error: 'x' was not declared in this scope } 

How to access elements x, y, z, w?

+4
source share
2 answers

You need an instance of your structure inside an anonymous union. I don’t know exactly what you want to achieve, but for example, something like this will work:

 struct Vector { union { float elements[4]; struct { float x, y, z, w; }aMember; }; float length() const { return aMember.x; } }; 
+5
source

What you created is not anonymous, but an anonymous type (which in itself is useless). You must create your anonymous type. This applies to both your structure and your association.

Adjust the header as follows:

 struct Vector { union { float elements[4]; struct { float x; float y; float z; float w; } v; } u; float length(); }; 

Now you can access your members as follows:

 u.elements[0] = 0.5f; if(uvx == 0.5f) // this will pass doStuff(); 
+4
source

Source: https://habr.com/ru/post/1338544/


All Articles