如何在C++中访问匿名union/struct成员?

Eon*_*nil 4 c++ anonymous-types

这个问题是我的.下面描述的代码正在构建中,没有任何问题.


我有这门课.

Vector.h

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

    float   length();
}
Run Code Online (Sandbox Code Playgroud)

Vector.cpp

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

如何访问成员x,y,z,w?

Kar*_*oor 5

您需要匿名联合中的结构实例.我不知道你想要什么,但是像这样的东西会起作用:

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

  float length() const
  {
    return aMember.x;
  }
};
Run Code Online (Sandbox Code Playgroud)