Hi
I'm currently trying to learn C++. I'm at the chapter on operator overloading and I have a question.
I've implemented a custom array class, MyEvenArray, and I've overloaded the [] operator as usual so that it returns a reference to an element of MyEvenArray. Now I'm curious if there's any way to overload the assignment TO said reference to allow for validation. The answer may well be, "No, that's impossible!" but I thought I'd ask.
To clarify, let's say my class code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// MyEvenArray, an array that only lets you add even numbers
MyEvenArray {
public:
...
int& operator[] (int index) {
return internalArray[index];
}
void setElement(int index, int element) {
if(element % 2 == 0) {
internalArray[index] = element;
}
}
private:
int internalArray[5];
};
|
Now, is there any way to do
1 2
|
MyEvenArray m();
m[0] = 3;
|
and have it fail as per the rules laid out in the setElement(int index, int element) function? I.e., can I have m[0] = 3 be equivalent to m.setElement(0,3) ?
I realize I could have internalArray be an array of MyEvenInts which have some special behaviour, but assuming I keep internalArray as an array of ints, is there any way to do what I want?