是否有更好的方法初始化引用成员以引用同一类中的另一个成员
Is there a better way to initialize reference members to reference another member in the same class
在任何人说任何话之前,我知道这可能是不推荐的,但我仍然很好奇是否有更好的方法来做这件事,或者是否有理由不去做这件奇怪的事。
我之所以开始研究这个问题,是因为我想直接使用类中语义命名的成员访问数组的元素,同时仍然能够迭代数组,而不必调用/创建一些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的答案更好。
相关文章:
- 具有引用成员的结构是否具有唯一的对象表示形式
- 初始化右值引用成员
- C++通过绑定到引用成员而缩短临时变量寿命?
- C++为具有引用成员变量的类创建复制构造函数
- 常量和引用成员函数限定符
- C++将引用成员绑定到构造函数参数
- 如果包含引用成员的类中缺少原始变量,为什么它仍然可以访问?
- 初始化指针或引用成员变量以指向另一个成员
- 将常量引用成员设置为临时变量是否安全
- 对象超出范围后,引用成员设置为 0
- 复制构造函数初始化初始化列表中的引用成员会导致指针悬空
- 使用默认构造函数引用成员变量初始化错误
- 如何从派生类访问引用成员变量?
- Visual Studio 2017 允许在构造函数中使用自身初始化引用成员.真的是合法的C++吗?
- 为什么当类具有引用成员时C++编译器不删除复制构造函数
- 引用成员到构造函数参数按值传递
- 在执行不平凡的构造函数之前引用成员
- 具有引用成员变量的多态性
- 从按值构造函数参数初始化的引用成员
- 深度复制包含引用成员(C++)的结构