I have a topic I'm confused on that I need some elaborating on. It's operator overloading with a const version and a non-const version.
// non-const
double &operator[](int idx) {
if (idx < length && idx >= 0) {
return data[idx];
}
throw BoundsError();
}
I understand that this lambda function, takes an index and checks its validity and then returns the index of the array data in the class. There's also a function with the same body but with the function call as
const double &operator[](int idx) const
Why do we need two versions?
For example, on the sample code below, which version is used in each instance below?
Array a(3);
a[0] = 2.0;
a[1] = 3.3;
a[2] = a[0] + a[1];
My hypothesis that the const version is only called on a[2]
because we don't want to risk modifying a[0]
or a[1]
.
Thanks for any help.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…