Hey I've just started learning about templates. I neede to create a template for an array.
this is the code I wrote:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
using namespace std;
template <class T> class Array
{
private:
T* data;
unsigned int size;
public:
Array<T> (unsigned int x)
{
size = x;
}
const T& operator[] (unsigned int index) const
{
if (index < 0 || index >= size () )
throw domain_error("Array index out of bounds");
return data[index];
}
unsigned int getSize () { return size; }
void add (const T&, unsigned int index)
{
if (index < 0 || index >= size () )
throw domain_error("Array index out of bounds");
else
data[index] = T;
}
void display ()
{
cout << "[" << data[0];
for (int i = 1; i < size < ++i)
cout << " , " <<data[i]
cout << "]" << endl;
}
};
int main ()
{
Array<int> arr(10);
for (int i = 0; i <arr.getSize(); ++i)
arr.add(i,i);
arr.display();
return 0;
}
|
and these are the errors I got:
1>testarray.cpp(50): warning C4018: '<' : signed/unsigned mismatch
1>testarray.cpp(29): error C2064: term does not evaluate to a function taking 0 arguments
1>testarray.cpp(28) : while compiling class template member function 'void Array<T>::add(const T &,unsigned int)'
1> with
1> [
1> T=int
1> ]
1>testarray.cpp(48) : see reference to class template instantiation 'Array<T>' being compiled
1> with
1> [
1> T=int
1> ]
1>testarray.cpp(32): error C2275: 'T' : illegal use of this type as an expression
1>testarray.cpp(48) : see declaration of 'T'
Firstly, I don't really understand the errors and I'll be glad if someone could explain the, to me. Also I'm not really sure why I'm getting there errors (I'm working with a book, and my code is pretty close to the one in the book)
thanks!