c++ - 需要 Union hack

标签 c++ c

我有一个表示顶点的结构。它具有 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/

相关文章:

c++ - stable_sort 不保持元素的顺序

c++ - 构造函数初始化列表: code from the C++ Primer,第16章

c 正则表达式找不到字符串

c++ - 如何确定 exe 文件是 .Net exe 还是常规 exe?

c++ - 为什么 const std::vector 将 const 应用于包含的对象?

c++ - 我可以在 C++ 中使用指针访问二维数组的元素吗?

c++ - 利用 sandy bridge 的硬件真随机数生成器?

c - 这个函数怎么写 C

C程序不读取文件

c - GNU ARM 嵌入式工具链安装问题