Reputation: 86155
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?
Upvotes: 4
Views: 6067
Reputation: 8614
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;
}
};
Upvotes: 5
Reputation: 1941
What you have created is not an anonymous member, but anonymous type (which is useless by itself). You have to create a member of your anonymous type. This concerns both your struct and your union.
Adjust the header like this:
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 like this:
u.elements[0] = 0.5f;
if(u.v.x == 0.5f) // this will pass
doStuff();
Upvotes: 4