Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This question is my mistake. The code described below is being built well with no problem.


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 the member x,y,z,w?

like image 641
eonil Avatar asked Jan 20 '23 14:01

eonil


1 Answers

You need an instance of your struct inside the anonymous union. I don't know exactly what you want to achive, but e.g. something like this would work:

struct Vector
{
  union
  {
    float elements[4];
    struct
    {
      float x, y, z, w;
    }aMember;
  };

  float length() const
  {
    return aMember.x;
  }
};
like image 146
Karl von Moor Avatar answered Feb 01 '23 22:02

Karl von Moor