したがって、次のようなベクター クラスがあります (わかりやすくするために、ほとんどのメソッドを省略しています)。
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;
?
EDIT : 要求に応じた完全なクラス仕様:
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();
};