I have a class which inherits from another class, and I wish to call [index]
to access the index'th element of some allocated storage.
Here is a minimal example:
class A
{
protected:
double *mem;
double operator[](const size_t index)
{
return mem[index];
}
}
class B : public A
{
void function()
{
double var = this->operator[](0);
}
}
So here I step around the problem by calling this->operator[](0)
which is kind of messy.
Is this the correct way to access elements of mem
considering that I don't have access to that variable from the derived class, or is there an alternative way?
Edit: I think it might be significant that I'm conforming to C++11, so can't call mem[0]
?
Edit, template classes
As discussed below, the compiler error I see isn't showing up for this example, because there are no templates here.
To reproduce the compiler error:
template
class A
{
protected:
double *mem;
double operator[](const size_t index)
{
return mem[index];
}
}
template
class B : public A
{
void function()
{
double var = this->operator[](0);
}
}
Possible Solutions
return this->operator[](0);
return (*this)[0];
return (this->mem)[0];
return *((this->mem)+0);
return (*this).mem[0];
return *((*this).mem+0);
... I think all of these do what I expect them to. Any more suggestions?
Even better solution:
return A::mem[0];
Exactly what I wanted!
No comments:
Post a Comment