所以我有一个看起来有点像这样的向量类(为了清楚起见,大部分方法都被去掉了):
class D3Vector {
private:
double _values[3];
public:
const double& operator[](const int index) const;
double& operator[](const int index);
};
double& D3Vector::operator[](const int index) {
assert(index >= 0 && index < 3);
return _values[index];
}
const double& D3Vector::operator[](const int index) const {
assert(index >= 0 && index < 3);
return _values[index];
}
在我的代码中,我将这个数组下标重载称为如下:
void func(D3Vector centre, double radius) {
double limits[6];
int i;
for (i = 0; i < 3; i++) {
// both these lines cause the error...
limits[i] = centre[i] - radius;
limits[i + 3] = centre[i] + radius;
}
...
}
但我在编译时收到此错误:
error: invalid types '<unresolved overloaded function type>[int]' for array subscript
现在,我已经摆弄了重载函数的签名,添加和删除引用符号,添加和删除 const,但我真的只是在这里猜测。
为像这样的实数向量类编写数组下标运算符重载的明智方法是什么,它允许我们执行简单的操作,例如:
instance[i] = 5.7;
和
new_value = instance[j] + 17.3;
?
编辑:完整的类规范,根据要求:
class D3Vector {
private:
double _values[3];
public:
// constructors - no args inits to 0.0
D3Vector();
D3Vector(const double x, const double y, const double z);
// binary + and -:
D3Vector operator+(const D3Vector& right);
D3Vector operator-(const D3Vector& right);
// unary -, reverses sign of components:
D3Vector operator-();
// binary *, scales components.
D3Vector operator*(const double scale);
// the same, as self-assignment operations:
D3Vector& operator+=(const D3Vector& right);
D3Vector& operator-=(const D3Vector& right);
D3Vector& operator*=(const double scale);
// subscript operator, for member data access.
const double& operator[](const int index) const;
double& operator[](const int index);
// dot product:
double dot(D3Vector& right);
// cross product:
D3Vector cross(D3Vector& right);
// shortcut to vector length:
double mod();
// faster way of getting length squared:
double mod_squared();
};