Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 需要工会黑客_C++_C - Fatal编程技术网

C++ 需要工会黑客

C++ 需要工会黑客,c++,c,C++,C,我有一个表示顶点的结构。它有x、y和z字段以及其他几个字段。最近,我得出结论,对于某些功能,我需要访问作为数组的顶点坐标。我不想用临时变量“污染”代码,也不想把所有看起来像v.y的地方都改成v.coord[1],这既不好也不优雅。所以我考虑使用工会。像这样的方法应该会奏效: struct { float x,y,z; } Point; struct { union { float coord[3]; Point p; }; } Vertex;

我有一个表示顶点的结构。它有x、y和z字段以及其他几个字段。最近,我得出结论,对于某些功能,我需要访问作为数组的顶点坐标。我不想用临时变量“污染”代码,也不想把所有看起来像
v.y
的地方都改成
v.coord[1]
,这既不好也不优雅。所以我考虑使用工会。像这样的方法应该会奏效:

struct {
  float x,y,z;
} Point;

struct {
    union {
        float coord[3];
        Point p;
    };
} Vertex;
这很好,但并不完美。point类在那里没有意义。我希望能够通过键入
v.y
(而不是
v.p.y
)来访问y坐标

你能建议一种破解方法来解决这个问题吗(或者告诉我这是不可能的)?

好的,这应该对你有用

struct {
    union {
        float coord[3];
        struct
        {
            float x,y,z;
        };
    };
} Vertex;

这段代码的作用是将数组与结构结合起来,因此它们共享相同的内存。因为结构不包含名称,所以它可以访问,而不是名称,就像联盟本身一样。

< P>一个好的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];
};
类点{
公众:

浮点和操作符[IN](int x){AsStRead(x;-))OK,不用担心,我给了你“up”以供你的评论:-不幸的是,它不是标准C++。它在技术上违反了联合存储规则。你只允许从你上次写的那个元素中读取。所以,如果你写了<代码> COORD(1)
,只能从
coord
数组中读取,不能从
x
y
z
中读取,如果写入
z
,则只能从
x
y
z
元素中读取,但不能从
coord
数组中读取。元素之间也可能存在填充这个结构是不太可能的,但它是可能的。说它是无效的C++是迂腐的,但有效的,抱怨。AFIK VC++表示“非标准扩展”。在GCC中,您可以通过一些标志来启用此功能。然而,C99/C++98,03,0x标准只有匿名联合,而不是匿名结构。@All:related:如果需要将其传递给C接口,还可以使用
const float*address()const{return coords_;}
。@aschepler:这可能也很有用,尽管如此,
&p[0]
将产生相同的结果。+1.任何一个合适的编译器设置为优化都会将它们直接内联到适当的位置,因此它将与任何联合黑客一样高效。你的方法的问题是它需要对代码进行一些更改。提问者似乎感兴趣的是具有访问点的数组样式,同时保持x/y/z样式,这样他就不必更改代码