ベクトルを実装しているので、配列として動作させたいと思っていました。それが、添字演算子を実装しようとした理由ですが、正しい動作を達成していません。
実装は次のようなものでした。
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
一部のスレッドは、代入演算子をオーバーロードするハンドラー クラスの使用を推奨しています。タスクを実行するためにハンドラー オブジェクトの使用を回避する方法があるのだろうかと思います。
前もって感謝します。
アルゼンチン出身のゴンサロ。