I tried to implement the operator[] for a container of mine. But I am really new to c++, and it seems I have an error in my implementation.
I declared them like this:
float& operator[](const int &idx);
const float& operator[](const int &idx) const;
which should be fine, it’s pretty much copy/paste from tutorials. Now, Quaternion.cpp looks like this:
float& Quaternion::operator[](const int &idx)
{
if(idx == 0)
{
return x;
}
if(idx == 1)
{
return y;
}
if(idx == 2)
{
return z;
}
if(idx == 3)
{
return w;
}
std::cerr << "Your Quaternion is only accessible at positions {0, 1, 2, 3}!"
<< std::endl;
return x;
}
const float& Quaternion::operator[](const int &idx)
{
if(idx == 0)
{
return const x;
}
if(idx == 1)
{
return const y;
}
if(idx == 2)
{
return const z;
}
if(idx == 3)
{
return const w;
}
std::cerr << "Your Quaternion is only accessible at positions {0, 1, 2, 3}!"
<< std::endl;
return x;
}
I get the error for the signature “const float& Quaternion::operator[](const int &idx)”.
Another thing which happened before, was that I couldn’t return 0 in case the boundaries got exceeded. Maybe I will, once this issue is resolved, but it gave me an error message before. I just returned x then, which makes me really unhappy.
You left out the trailing
constmodifier from the second (const) operator implementation: