c++ - 有没有更好的方法来初始化引用成员以引用同一个类中的另一个成员

标签 c++ class reference constructor const-cast

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

我开始研究这个是因为我想直接使用类中语义命名的成员访问数组的元素,同时仍然能够遍历数组而不必调用/创建一些 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;
}

编辑

我是个白痴……你可以像 Jonathan Wakely 说的那样去做。

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];
};

关于c++ - 有没有更好的方法来初始化引用成员以引用同一个类中的另一个成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15512299/

相关文章:

c++ - 在函数返回中返回新分配的 shared_ptr 的引用是否合法?

c++ - 将 vector 传递给函数时,默认参数(如果有)应该是什么?

c++ - 我可以在 C++ 中使用智能指针作为类成员吗?

python - 关于Python中__init__的正确使用

objective-c - ios5 上的dismissViewControllerAnimated 崩溃

C++ 结构化绑定(bind) : What is the standard order of destruction?

c++ - 使用AKAZE时opencv 3.0下和windows 7下mingw下的异常

c++ - 错误 : "expected class name"

reference - 为什么我可以返回对本地文字的引用,而不是对变量的引用?

java - 指针引用指向哪个对象?