1

ベクトルを実装しているので、配列として動作させたいと思っていました。それが、添字演算子を実装しようとした理由ですが、正しい動作を達成していません。

実装は次のようなものでした。

template <typename value_type>
class Vector{ 
    private:
    value_type ** vector ; 
    long size ; 
    long usedSize ; 

    public: 
    /.../ 
    value_type & operator [] (long) ; // For writing.
    const value_type & operator [] (long) const ; // For reading.
    /.../
}

template<typename value_type> 
value_type & Vector<value_type>::operator[] ( long index ) {
    if ( index < 0 || index > usedSize ) 
        return out_of_range () ; 
    else {
        vector[index] = new value_type () ; 
        usedSize++ ; 
        return *(vector[index]) ;
    }
} 

template<typename value_type> 
const value_type & Vector<value_type>::operator[] ( long index ) const {
    if ( index < 0 || index > usedSize ) 
        return out_of_range () ; 
    else { return (*vector[index]) ; }
}

次に、これを使用してオブジェクトの動作をテストします。

int main (void) { 
    Vector<int> * v = new Vector ( 10 ) ; // Creates a vector of 10 elements.
    (*v)[0] = 3 ; 
    int a = (*v)[0] ; 
    cout << "a = " << a << endl ;
}

そして、私は実行からこれを取得します:

$> a = 0 

一部のスレッドは、代入演算子をオーバーロードするハンドラー クラスの使用を推奨しています。タスクを実行するためにハンドラー オブジェクトの使用を回避する方法があるのだろうかと思います。

前もって感謝します。

アルゼンチン出身のゴンサロ。

4

1 に答える 1

1

あなたは間違っていると仮定します

cout << "a =" << (*v)[0] << endl;

const value_type & Vector::operator[] (長いインデックス) const

使用されます。

実は2回とも

value_type & Vector::operator[]

以前の値を新しい値に「置き換える」ように使用されます(同時にメモリリークが発生します)

以下が役立つはずです

value_type & Vector<value_type>::operator[] ( long index ) {
    if ( index < 0 || index > usedSize )
        ///out of bounds handling
    else {
        if(vector[index]== 0)
        {
            vector[index] = new value_type () ;
            usedSize++ ;
        }
        return *(vector[index]) ;
    }
}
于 2013-06-01T23:52:21.470 に答える