【发布时间】:2017-04-13 17:23:33
【问题描述】:
这是来自 Box2d 物理引擎的 b2Math.h 的代码。
struct b2Vec2
{ ...
/// Read from and indexed element.
float operator () (int i) const
{
return (&x)[i];
}
/// Write to an indexed element.
float operator () (int i)
{
return (&x)[i];
}
...
float x, y;
}
为什么我们不能只使用 SomeVector.x 和 SomeVector.y 来读取/写入矢量坐标?以及return (&x)[i]; 行的实际工作原理是什么?我的意思是,对结构的 x 组件的引用之后的数组刹车 [] 对我来说并不清楚。
提前感谢您的回复。
【问题讨论】:
-
"为什么我们不能只使用 SomeVector.x 和 SomeVector.y 来读取/写入矢量坐标?"你如何声明
SomeVector?这不在您的代码示例中。 -
(&x)[i]对除0之外的任何i表现出未定义的行为,因为它将尝试在未分配给此类数组的内存中执行数组索引。 -
修改
operator()时出错:应该返回float&。 -
您似乎缺少重要信息来完全回答问题。但是,“为什么我们不能只使用 SomeVector.x 和 SomeVector.y 来读取/写入矢量坐标?”很简单,你可以:)
-
@CoryKramer 我很确定在大多数实现中
x和y在内存中是相邻的。这不能保证吗? (注意我不是 OP。)
标签: c++ struct operator-overloading box2d