Array subscript operator overloading
I am having trouble understanding the difference between Array obj;
and Array* obj = new Array;
while overloading the array index operator []
. When I have a pointer to the object, I get these error messages on VS 2010.
error C2679: bina开发者_JS百科ry '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) could be 'Array &Array::operator =(const Array &)' while trying to match the argument list '(Array, int)'
#include <iostream>
class Array
{
int arr[10] ;
public:
int& operator[]( int index )
{
return arr[index] ;
}
};
int main()
{
//Array* obj = new Array; Error
Array obj; // Correct
for( int i=0; i<10; ++i )
obj[i] = i;
getchar();
return 0;
}
Can some one explain the rationale between the two kind of instances for operator overloading? Thanks.
In case of Array *obj
, obj[i]
is the equivalent of *(obj+i)
, so it evaluates into an Array
object.
You would have to do
int main()
{
Array* obj = new Array;
for( int i=0; i<10; ++i )
(*obj)[i] = i;
getchar();
return 0;
}
You defined operator[]
for Array
, not for Array*
. In the commented-out code, you create an Array*
. In fact, you cannot overload an operator for any pointer type. Applying []
to a pointer treats it as an array, converting the array indexing into pointer arithmetic. Thus, applying []
to an Array*
yields an Array
(really an Array&
). You can't assign an int
to an Array
because you didn't define that (and don't want to, either).
Modern, well-written C++ uses the keyword new
very seldom. You should not be suspicious that your C++ code doesn't contain the keyword new
. You should be suspicious every time it does!
精彩评论