如何为集合建立索引并允许每个索引变量具有自定义设置器?
所以我有一个名为 Vertex
的对象,它包含一些参数(我们称它们为 sx
、sy
和 i
)。 sx
、sy
和 i
每个都有特殊的设置器:即 Vertex
看起来像
class Vertex {
public:
float sx() { return sx; };
void setSx(float val) {
val > 0 ? sx = val : sx = 0;
};
float sy() { return sy; };
void setSy(float val) {
val >= 0 ? sx = val * 0.5 : sx = -val;
};
float i() { return i; };
void setI(float val) { i = val; };
private:
float sx, sy, i;
};
我希望能够迭代 Vertex
的参数,而不必调用每个 setter。例如:
Vertex* v = new Vertex();
for (int i = 0; i < Vertex::size; i++)
(*v)[i] = 0;
或者类似的东西,而不必使用更笨重的符号:
Vertex* v = new Vertex();
v->sx = 0;
v->sy = 0;
v->i = 0;
有没有什么方法可以以更优雅的方式实现这一点,而不仅仅是重载 operator[]
和使用 switch< /代码>声明?我不需要使用上面演示的确切符号,我只需要一种方法来迭代
Vertex
的组件,而不关心每个组件的自定义设置器。
So I have an object called Vertex
which contains some parameters (let's call them sx
, sy
and i
). sx
, sy
and i
each have special setters: ie, Vertex
looks something like
class Vertex {
public:
float sx() { return sx; };
void setSx(float val) {
val > 0 ? sx = val : sx = 0;
};
float sy() { return sy; };
void setSy(float val) {
val >= 0 ? sx = val * 0.5 : sx = -val;
};
float i() { return i; };
void setI(float val) { i = val; };
private:
float sx, sy, i;
};
I would like to be able to iterate through a Vertex
's parameters without having to call each setter. For example:
Vertex* v = new Vertex();
for (int i = 0; i < Vertex::size; i++)
(*v)[i] = 0;
or something like that, instead of having to use the clunkier notation:
Vertex* v = new Vertex();
v->sx = 0;
v->sy = 0;
v->i = 0;
Is there any way to accomplish this in a more elegant way than just overloading operator[]
and using a switch
statement? I don't need to use the exact notation I demonstrated above, I just need a way to iterate through the components of a Vertex
without caring about the custom setters of each of them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
窃取 James Curran 的内容(并稍作修改):(
James 如果您想声明此方法,我将删除)。 :-)
Stealing from James Curran (and adapting slightly):
(James if you want to claim this method I will delete). :-)
您可以创建一个指向浮点数的指针数组,并对其进行索引,但我不确定结果是否符合“最优雅”的条件
You could create an array of pointers to floats, and index off that, but I'm not sure if the result would qualify as "most elegant"
重置方法怎么样()。
或者只是在构造函数中执行此操作,以便在创建对象时正确初始化对象。
How about a reset method().
Or just do it in the constructor so when you create it the object is correctly initialized.