0

テンプレート化された型を取り、それをリスト/配列の最後に追加する関数を作成しようとしていますが、回避策が見つからないようなエラーが発生しています。私はテンプレートを初めて使用するので、テンプレートの使用方法に問題があるのか​​どうかわかりません。

これが私が持っているコードの相対的な部分です:

// MyArray.h

// insure that this header file is not included more than once
#pragma once
#ifndef MYARRAY_H_
#define MYARRAY_H_

template <class elemType>
class MyArray
{
private:
  int _size;        // number of elements the current instance is holding
  int _capacity;    // number of elements the current instance can hold
  int _top;         // Location of the top element (-1 means empty)
  elemType * list;  // ptr to the first element in the array

public:
// Ctors
    MyArray(); // default
    MyArray(int capacity); // initialize to capacity
    MyArray( MyArray & original); // copy constructor

// Dtor
    ~MyArray();

// METHODS
// Add
    // Takes an argument of the templated type and
    // adds it to the end of the list/array
    void Add(const elemType & elem);
};

// =============================================================================

/* ... */

// METHODS
// Add
    // Takes an argument of the templated type and
    // adds it to the end of the list/array
    template <class T>
    void MyArray<T>::Add(const elemType & elem)  // error C4430 and C2143
    {
        list[ _size + 1 ] = elem; // Place item on the bottom of the stack
    } // error C2244


#endif

そして、私はこれらのエラーを受け取ります:

Error   1   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int               c:\...\myarray.h    80  1   Testing_Grounds
Error   2   error C2143: syntax error : missing ',' before '&'                                                      c:\...\myarray.h    80  1   Testing_Grounds
Error   3   error C2244: 'MyArray<elemType>::Add' : unable to match function definition to an existing declaration  c:\...\myarray.h    83  1   Testing_Grounds

これに関する助けをいただければ幸いです。

4

2 に答える 2

0
template <class T>
 void MyArray<T>::Add(const elemType & elem)  // error C4430 and C2143
 {
   //...
 } 

ここでelemType(関数パラメーターに)何がありますか?する必要がありますT。またはTする必要がありますelemType

template <class T>
void MyArray<T>::Add(const T & elem)  //fixed!
{
  //...
}

クラステンプレートメンバーの定義は、ファイルではなく、ヘッダーファイル自体に含める必要があることに注意してください.cpp

于 2012-11-11T02:13:33.407 に答える
0

ヘッダーでは、を使用<class elemType>し、cppでは使用します<class T>

cppで、をに変更すると<class T><class elemType>すべてが正常になります。MyArray<T>MyArray<elemType>

于 2012-11-11T02:14:16.680 に答える