I am trying to implement my own array wrapper. I overloaded [] operators that returns address of element in array. However when I dynamically allocate the ArrayWrapper class in main, it is not working.
Why is it not working? Is it because variable arr is a pointer?
I get these errors:
Description Resource Path Location Type cannot bind 'std::ostream {aka std::basic_ostream}' lvalue to 'std::basic_ostream&&' Cviceni.cpp /Cviceni/src line 25 C/C++ Problem
Description Resource Path Location Type no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'ArrayWrapper') Cviceni.cpp /Cviceni/src line 25 C/C++ Problem
Working code
ArrayWrapper arr(250);
try
{
for(int i = 0; i < arr.getSize(); i++)
{
arr[i] = i + 1;
cout << arr[i] << endl;
}
}
catch(std::range_error& e)
{
cout << e.what() << endl;
}
cout << "End..." << endl;
return 0;
}
Not working code:
ArrayWrapper *arr = new ArrayWrapper(250);
try
{
for(int i = 0; i < arr->getSize(); i++)
{
arr[i] = i + 1;
cout << arr[i] << endl;
}
}
ArrayWrapper implementation:
class ArrayWrapper
{
private:
int size;
int *elements;
public:
ArrayWrapper(int n) : size(n), elements(new int[n])
{
for(int i = 0; i < size; i++)
elements[i] = 0;
};
~ArrayWrapper(){delete []elements;};
int& operator[](int i)
{
if(i >= size || i < 0)
{
throw range_error("Out of range");
}
return elements[i];
};
int getSize(){ return size;};
};