【发布时间】:2017-05-03 13:49:33
【问题描述】:
我正在尝试自己构建一个 2D 矢量类。
当我在寻找其他人实现的示例代码时,我发现了这个:
class Vector2D {
public:
// components
double x, y;
Vector2D() : x( 0.0 ), y( 0.0 ) { }
// returns reference to the specified component (0-based indexing: x, y)
inline double& operator[] ( const int& index ) {
return ( &x )[ index ];
}
}
[] 运算符是如何重载的?我怎么理解(&x)[index]?
【问题讨论】:
-
你发现了垃圾。将您的学习材料更改为 makes sense.
-
我相信这个例子是未定义的行为。它依赖于
y紧跟在内存中的x之后,我不确定这是否得到保证。 -
const int& index是过早的悲观主义。它增加了一层没有任何增益的间接层。
标签: c++ class operator-overloading