是否有更好的方法初始化引用成员以引用同一类中的另一个成员

Is there a better way to initialize reference members to reference another member in the same class

本文关键字:引用 成员 一类 另一个 更好 方法 初始化 是否      更新时间:2023-10-16

在任何人说任何话之前,我知道这可能是不推荐的,但我仍然很好奇是否有更好的方法来做这件事,或者是否有理由不去做这件奇怪的事。

我之所以开始研究这个问题,是因为我想直接使用类中语义命名的成员访问数组的元素,同时仍然能够迭代数组,而不必调用/创建一些getter或setter方法。

我有一个类定义,看起来像这样。

class Vertex{
    public:
    Vertex(float x,float y,float z,float w);
    float v[4];
    float &x,&y,&Z,&w;
};

和一个看起来像这样的构造函数。我的问题是,有没有更好的方法来做我在构造函数中正在做的事情?

Vertex::Vertex(float vx,float vy,float vz,float vw):
    x(*const_cast<float*>( &this->v[0] )),
    y(*const_cast<float*>( &this->v[1] )), 
    z(*const_cast<float*>( &this->v[2] )),
    w(*const_cast<float*>( &this->v[3] ))
{
    v[0]=vx;
    v[1]=vy;
    v[2]=vz;
    v[3]=vw;
}

编辑

我是个白痴。。。你可以像乔纳森·韦克利说的那样做。

x(v[0]) 

我想我以前试过的时候还有其他问题。哦,好吧。

Vertex::Vertex(float vx,float vy,float vz,float vw):
    v { vx, vy, vz, vw },
    x(v[0]),
    y(v[1]), 
    z(v[2]),
    w(v[3])
{
}

我会避免在这里写推荐成员。原因是引用成员阻止默认的(编译器生成的(复制/赋值特殊成员。

class Vertex{
  public:
    Vertex(float x,float y,float z,float w)
        : v { x, y, z, w } { }
    float &x() { return v[0]; }
    float &y() { return v[1]; }
    float &z() { return v[2]; }
    float &w() { return v[3]; }
    float const &x() const { return v[0]; }
    float const &y() const { return v[1]; }
    float const &z() const { return v[2]; }
    float const &w() const { return v[3]; }
  private:
    float v[4];
};

你也可以走这条路:

class Vertex
{
public:
  float x;
  float y;
  float z;
  float w;
  Vertex(float x, float y, float z, float w);
  float&
  operator[](int i)
  { return *(&x + i); }
  float
  operator[](int i) const
  { return *(&x + i); }
};

也许,这个变体更好(与其他替代方案相比(,因为它需要更少的代码,并使您能够以数组样式迭代Vertex

就我个人而言,我最喜欢@se的答案,但我会给你一个替代方案。

struct Vector4 {
    float x;
    float y;
    float z;
    float w;
};
union VectorUnion {
    Vector4 vector;
    float array[4];
};

然后,您可以在Vertex类中使用VectorUnion,也可以单独使用。。。

我担心这是一个C结构,C++结构略有不同(它包括vtable等(,但我认为它应该可以工作。

再说一遍,我认为@she的答案更好。