by Bar Zohan
5. April 2010 23:34
As you know in c++ arrays can not be initiated with a dynamic variable but they can be used with constant variables or using defines etc.
So to overcome this problem you can write an array class which can be initiated with dynamic variables.
And here is the code;
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
using std::ostream;
using std::istream;
template< typename T >
class Array
{
/*friend ostream& operator<<(ostream&,const Array<T>&);*/
public:
Array(int size)
{
Size = (size > 0 ? size : 10);
ptr = new T[Size];
}
Array(const Array ©Array) : Size(copyArray.Size)
{
ptr = new T[Size];
for(int i=0;i<Size;i++)
{
ptr[i] = copyArray.ptr[i];
}
}
~Array()
{
delete [] ptr;
}
int GetSize() const
{
return Size;
}
const Array &operator=(const Array &right)
{
if(Size != right.Size)
{
delete [] ptr;
Size = right.Size;
ptr = new T[Size];
}
for(int i=0;i<Size;i++)
{
ptr[i] = right.ptr[i];
}
return *this;
}
bool operator==(const Array &right)
{
if(Size != right.Size)
return false;
for(int i=0;i<Size;i++)
if(ptr[i] != right.ptr[i])
return false;
return true;
}
T &operator[](int index)
{
if(index < 0 || index > Size -1)
{
std::cerr << "\nIndex out of range" << endl;
exit(1);
}
return ptr[index];
}
T operator[](int index) const
{
if(index < 0 || index > Size -1)
{
std::cerr << "\nIndex out of range" << endl;
exit(1);
}
return ptr[index];
}
bool operator!=(const Array &right)
{
return !(*this == right);
}
private:
T *ptr;
int Size;
};
template <typename T>
ostream& operator<<(ostream &output,const Array<T> &a)
{
for(int i=0;i<a.GetSize();i++)
{
output << a[i] << endl;
}
return output;
}