我有一个表示顶点的结构。它具有 x、y 和 z 字段以及其他几个字段。最近我得出结论,对于某些功能,我需要以数组的形式访问顶点的坐标。我不想用临时变量“污染”代码或将所有看起来像 v.y
的地方更改为这个 v.coord[1]
这既不好也不优雅的。所以我想到了使用 union 。这样的事情应该有效:
struct {
float x,y,z;
} Point;
struct {
union {
float coord[3];
Point p;
};
} Vertex;
这很好,但并不完美。积分等级在那里毫无意义。我希望能够通过键入 v.y
(而不是 v.p.y
)访问 y 坐标。
你能建议一个 hack 来解决这个问题吗(或者告诉我这是不可能的)?
最佳答案
一个好的 C++ 方法是使用返回对元素的引用的命名访问器:
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];
};
使用这种方法,给定一个 Point p;
,您可以同时使用 p[0]
和 p.X()
来访问初始值内部 coords_
数组的元素。
关于c++ - 需要 Union hack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4527955/