3

したがって、次のようなベクター クラスがあります (わかりやすくするために、ほとんどのメソッドを省略しています)。

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();
};
4

1 に答える 1

9

[]コメンターが指摘しているように、かっこの代わりにかっこを使用して関数を呼び出そうとすると、このエラーがポップアップします()。これはまさにここで起こっていることであり、コード例を単純化したため明らかではありませんでした。

質問では、呼び出された関数を投稿して例を示します-これは実際には継承されたクラスのコンストラクターでした(したがって、すべてのコードをfunc投稿するのではなく、単純化しました)。

基本クラスには、知っておく必要があるすべてが含まれています。

class D3Shape {
  protected:
    double l[6];
    virtual void initilise_limits() = 0;
  public:
    virtual bool contains(D3Vector point) = 0;
    vector<double> limits();
};

つまり、私が探していた をl格納するプライベート メンバー変数と、コンテナー内のそれらを取得するための関数を混同していました。これは、同じ行で実際の配列添え字オーバーロード クラスを (成功して) 使用していたという事実によって複雑になり、混乱しました! ファイルのコンパイラエラー「列番号」は、実際には の後の最初の文字を指していたため、さらに混乱していました。double[6]limits()std::vector<double>=

コメントをくださった皆様、どうもありがとうございました。

于 2013-01-20T09:50:56.623 に答える