[英]How to access anonymous union/struct member in C++?
这个问题是我的错 。 下面描述的代码正在构建中,没有任何问题。
我有这门课。
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
}
如何访问成员x,y,z,w?
您需要匿名联合中的结构实例。 我不知道你想要什么,但是像这样的东西会起作用:
struct Vector
{
union
{
float elements[4];
struct
{
float x, y, z, w;
}aMember;
};
float length() const
{
return aMember.x;
}
};
你创建的不是匿名成员,而是匿名类型(它本身没用)。 您必须创建匿名类型的成员。 这涉及你的结构和你的联盟。
像这样调整标题:
struct Vector
{
union
{
float elements[4];
struct
{
float x;
float y;
float z;
float w;
} v;
} u;
float length();
};
现在您可以像这样访问您的成员:
u.elements[0] = 0.5f;
if(u.v.x == 0.5f) // this will pass
doStuff();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.