I am trying to overload the [] operator.The problem I am getting is that it either sys that It excepts one argument or it must be a non-static member function.Tried to make it a stand-alone function, a friend function, but I still fail. Can someone please help.
This is when I make it a standalone function.The error is must be non-static.When I make it a friend, the error is Except only one argument
int Array :: operator[](int subscript)const // return the value at subscript if found
{
if(subscript < 0 || subscript >= size)
{
cout<<" Error 404"<<endl;
exit(EXIT_FAILURE);
}
else
{
return ptr[subscript];
}
}
voidoperator[]( int value, int _index) // store the value at the index specified
{
//int _index;
if(_index < 0 || _index >= size)
{
cout<<" Error 404 "<<endl;
exit(EXIT_FAILURE);
}
else
{
ptr[_index] = value;
}
}
In the first one I return the value provided its in the range specifed.But in the second one I need to store the value passed in the index passed.That is the problem I am having...
okay, I think I get your code, but then I get lost on the way.
What I want to chieve is change the number.
I simply want to store the value at the index. eg suppose the arguments passed are value = 10 && _index = 4; then ptr[4] should be equal to 10;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
voidoperator[]( int value, int _index) // store the value at the index specified
{
//int _index;
if(_index < 0 || _index >= size)
{
cout<<" Error 404 "<<endl;
exit(EXIT_FAILURE);
}
else
{
ptr[_index] = value;
}
}
Overloaded subscript operators usually return a reference to the item at that index, and that item can be modified. That way, you don't have to do any assignments internally. It also let's you do:
main.cpp:20:6: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]
In file included from main.cpp:1:0:
array.h:35:7: note: candidate 1: int Array::operator[](int) const
array.h:40:8: note: candidate 2: int& Array::operator[](size_t)
main.cpp:20:10: error: lvalue required as left operand of assignment
May someone please explain to me what certain things do in that code and how.Cause I cannot seem to figure them out.