问题描述
我正在尝试制作自定义矢量数据结构。它将始终包含 4 个浮点值。我想通过其属性名称访问它,但也可以通过运算符 [] 访问它,因此也可以使用索引访问它,例如大批。它应该可以通过运算符 [] 进行编辑,例如向量或数组。 到目前为止,我已经这样做了:
struct vec4
{
float* x;
float* y;
float* z;
float* w;
vec4() : data(4,0.0f) { Init(); }
vec4(float x,float y,float z,float w)
{
data = std::vector<float>{ x,y,z,w };
Init();
}
float* operator[](int i) const
{
switch (i)
{
case 0: return x;
case 1: return y;
case 2: return z;
case 3: return w;
default: __debugbreak();
}
}
private:
std::vector<float> data;
void Init()
{
std::vector<float>::iterator start = data.begin();
this->x = &(*++start);
this->y = &(*++start);
this->z = &(*++start);
this->w = &(*start);
}
};
解决方法
拥有单独的成员,然后使用 switch 语句几乎是做到这一点的方法。不过你不需要向量,可以像
一样编写类books_xmls
Year\...
Month\...
Day\...
books
,
怎么样
struct vec4
{
vec4() : vec4(0,0) {}
vec4(float x,float y,float z,float w) : data{ x,y,z,w } {}
float operator[](int i) const { return data[i]; }
float& operator[](int i) { return data[i]; }
float at(int i) const { return data.at(i); }
float& at(int i) { return data.at(i); }
float x() const { return data[0]; }
float y() const { return data[1]; }
float z() const { return data[2]; }
float w() const { return data[3]; }
float& x() { return data[0]; }
float& y() { return data[1]; }
float& z() { return data[2]; }
float& w() { return data[3]; }
private:
std::array<float,4> data;
};