联盟需要破解 [英] Union hack needed
问题描述
我有一个结构的重新presents一个顶点。它具有的x,y和z领域以及其他几个人。最近,我来到结论,对于某些功能,我将需要访问的顶点坐标的数组。我不想污染的code。与临时变量或更改像这样所有地方 VY
这个 v.coord [1]
这是不是很好也不优雅。所以我想过使用工会。像这样的东西应该工作:
I have a struct that represents a vertex. It has x, y and z fields as well as several others. Recently I came into conclusion that for certain functionality I will need to access the coordinates of the vertex as an array. I didn't want to "pollute" the code with temporary variables or change all places that look like this v.y
to this v.coord[1]
which is not nice nor elegant. So I thought about using a union. Something like this should work:
struct {
float x,y,z;
} Point;
struct {
union {
float coord[3];
Point p;
};
} Vertex;
这是不错的,但并不完美。点类没有点在那里。我希望能够访问只需键入 V.Y
(而不是 v.p.y
),y坐标。结果
你可以建议一个黑客来解决这个(或告诉我,这是不可能的)?
This is good, but not perfect. The point class has no point being there. I want to be able to access y coordinate simply by typing v.y
(and not v.p.y
).
Can you suggest a hack to solve this (or tell me that it is not possible)?
推荐答案
一个很好的C ++的方法是使用一个名为访问返回引用的元素:
A good C++ approach is to use named accessors that return references to the elements:
class Point {
public:
float& operator[](int x) { assert(x <= 2); return coords_[x]; }
float operator[](int x) const { assert(x <= 2); return coords_[x]; }
float& X() { return coords_[0]; }
float X() const { return coords_[0]; }
float& Y() { return coords_[1]; }
float Y() const { return coords_[1]; }
float& Z() { return coords_[2]; }
float Z() const { return coords_[2]; }
private:
float coords_[3];
};
通过这种方式,给定一个 P点;
,您可以同时使用 P [0]
和的pX()
来访问内部 COORDS的初始元素_
阵列。
With this approach, given a Point p;
, you can use both p[0]
and p.X()
to access the initial element of the internal coords_
array.
这篇关于联盟需要破解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!