Jessica said:
Hi,
I started implementing the wrapper class for vector<double> but I
ran into some trouble. Hope some of you can help me.
First of all, I was trying to over load the [] operator:
// operator overloading. _tsVal is a private member declared as
vector<Type>
Type& operator[](int its) const
{
return _tsVal.at(its);
}
When you declare the function to be "const" you are promising that the
function does not change the internal state of the object. So you can't
change _tsVal, for instance, and you can't call another function unless it
is also const. If you look at the code for <vector> I am sure you will see
that the "at" function has a const version which returns a const reference
and a non-const version which returns a non-const reference. When you wrote:
return _tsVal.at(its);
you were calling the const version of at() -- calling the non-const version
would violate const-correctness. Hence the return type was a const Type &
which you then tried to convert to a non-const Type &. I wasn't impressed
with the error message you got but that's life in template city.
It is usual for a const function to return only a const reference or const
pointer. You can write both in the same class:
Type &operator [] (int);
const Type &operator [] (int) const;
These are two different functions because they have different signatures
(the const declaration counts as part of the signature). I suggest you
implement both of these functions in your class and I think all will be
well.
BTW the practical implication of implementing both is that if your client
has a const object he can still use operator [] on the right hand side:
function yadda(const TimeSeries &ts)
{
double foo = ts[4]; // calls operator [] (int) const -- legal
ts[4] = 12.2; // calls operator [] (int) -- not legal
}
If he has a non-const object he can use operator [] on either side of the
assignment.
<snip>
Cy