-1

私のcompsciクラスでジェネリックスとテンプレートを紹介しました。任意のデータ型の格納と取得をサポートする汎用コンテナクラスを作成するように依頼されました。配列のサイズを変更する場合を除いて、すべての機能が正常に機能しています。挿入関数内でサイズ変更の呼び出しがあります。

template< typename T >
void Container< T >::insert( T  magic)
{
    if (index == size)
    {
        resize();
    }
    containerPtr[index] = magic;
    index++;
}

サイズ変数は配列のサイズであり、インデックスは次の挿入位置です。

これが私のサイズ変更機能です:

template< typename T >
void Container< T >::resize()
{
    int doubSize = size * 2;
    Container< T > temp(doubSize);
    for (int i = 0; i < size; i++)
    {
        temp[i] = containerPtr[i];      // error 1 here
    }
    *containerPtr = temp;               // error 2 here
    size = doubSize;
}

私の過負荷=

template< typename T >
const T Container< T >::operator=(const T& rhs)
{
    if(this == &rhs)
    {
        return *this;
    }
    return *rhs;
}

コンパイルしようとすると、次のエラーが発生します。

1: error C2676: binary '[': 'Container<T>' does not define this operator or a conversion to a type acceptable to the predefined operator
2: error C2679: binary '=': no operator found which takes a right-hand operand of type 'Container<T>' (or there is no acceptable conversion)

ここでどこが間違っているのかわかりません...

4

3 に答える 3

3

このエラー

temp[i] = containerPtr[i];      // error 1 here

おそらく、operator[](size_t)角かっこでコンテナの要素にアクセスできるようにを定義していないためです。これらのconstおよびnon-const演算子のようなものが必要です。

T& operator[](std::size_t index) { return containerPtr[index]; }
const T& operator[](std::size_t index) const { return containerPtr[index]; }

containerPtrオブジェクトを保持する動的なサイズの配列があると仮定しTます。そしてこの行:

*containerPtr = temp;               // error 2 here

間違っている。のタイプ*containerPtrT、であり、をに割り当てようとしContainer<T>ていTます。これが機能する可能性は低いです。

ループと割り当ての代わりに使用することをお勧めしますstd::copyが、割り当ての精神に反する可能性があることは理解しています。

于 2012-11-27T15:30:45.083 に答える
1

2:エラーC2679:バイナリ'=':タイプ'Container'の右側のオペランドをとる演算子が見つかりません(または受け入れ可能な変換がありません)

より重要なエラーです、それはあなたがタイプが上にあると信じているものは何でも述べています

* containerPtr = temp;

このコード行は正しくありません。container<T>あなたがやろうとしていることであるT値にaを割り当てることは不可能です。tempを動的に割り当てられた正しいサイズのTの配列へのポインターに変更した後(そして割り当てのポインターderefを削除した後)、他のエラーは自然に消えます。前の配列を削除するのを忘れた場合のメモリリークも修正する必要があることに注意してください。

于 2012-11-27T15:36:05.637 に答える
0

エラー1:operator[]Containerクラスを定義する必要があることを確認してください

エラー2:オーバーロードするときは次の署名を使用する必要がありますoperator=

template< typename T >
const T Container<T>::operator=(const Container<T>& rhs)
{ 
   ...
}
于 2012-11-27T15:30:43.637 に答える