operator overloading
1 2 3 4 5 6 7 8
|
Object & operator[]( int index )
{
#ifndef NO_CHECK
if( index < 0 || index >= currentSize )
throw ArrayIndexOutOfBounds( );
#endif
return objects[ index ];
}
|
I was wondering that does the & mean in the line of code?
I was wondering that does the & mean in the line of code? |
It returns the object at the current index, not a copy of it.
1 2 3 4 5 6
|
int a = 5;
int &b = a; // b and a are the same
int c = a; // c has the value of a
b = 64; // a and b are 64
c = 43; // only c is 43
|
if you didnt have the ampersand you would return a copy and it couldnt be modified.
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
|
class Array
{
int num[3];
public:
Array()
{
num[0] = 65;
num[1] = 315;
num[2] = 647;
}
int& operator[](int index)
{
return num[index];
}
const int getNumber(int index)
{
return num[index];
}
};
int main(int argc, char *argv[])
{
Array arr;
arr[0] = 5; // :)
arr.getNumber(0) = 3; // error cant edit the copy :/
std::cout << arr[0];
}
|
Last edited on
Topic archived. No new replies allowed.