I'm trying to make a function that takes a templated type and adds it to the end of the list/array and I'm running into an error that I can't seem to find a way around. I'm new to templates so I'm not sure if it's a problem with how I'm using templates or something else.
Here is the relative portion of code that I have:
// 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
And I'm getting these errors:
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
Any help with this would be much appreciated!
template <class T>
void MyArray<T>::Add(const elemType & elem) // error C4430 and C2143
{
//...
}
Here what is elemType
(in the function parameter)? It should be T
. Or T
should be elemType
.
template <class T>
void MyArray<T>::Add(const T & elem) //fixed!
{
//...
}
Note that the definition of the class template members should be in the header file itself, not in the .cpp
file.