C++ using 'this' as a parameter
I have a class which looks approximately like this:
class MeshClass
{
public:
Anchor getAnchorPoint(x, y)
{
return Anchor( this, x, y );
}
private:
points[x*y];
}
I want to make another class which represents an "Anchor" point which can get access to the Mesh and modify the point, like this:
class Anchor
{
public:
Anchor(&MeshClass, x, y)
moveAnchor(x, y);
}
The problem is when I try to make the Anchor
in the MeshClass::getAnchorPoint
method, something like return Anchor(this, x, y)
but because this
is const I can't. As a workaround until I get this figured out I have Anchor accepting a reference to the point and moveAnchor moves the point directly.
Edit: The problem was most likely something dumb I was doing with trying to use a Reference. I changed to using a pointer like I normally would and I can pass in this
with no complaints from the compiler. I'm almost certain I was getting an error related to this being const, but I can't recreate it so I must just 开发者_运维技巧be out of my mind.
In C++, this is a pointer, not a reference. You could do something like this:
class Anchor; //forward declaration
class MeshClass
{
public:
Anchor getAnchorPoint(int x, int y)
{
return Anchor(*this, x, y );
}
private:
int points[WIDTH*HEIGHT];
}
class Anchor
{
public:
Anchor(MeshClass &mc, int x, int y);
}
The constness of this is not a problem. The pointer itself is const, not the value it points to.
Your real problem is here:
class MeshClass
{
public:
Anchor getAnchorPoint(x, y)
{
return Anchor( *this, x, y );
}
private:
points[x*y];
}
Why do you think this
is const? this
is a pointer, not a reference. Shouldn't it be return Anchor( *this, x, y);
?
Could you change Anchor to accept a const MeshClass&
as parameter, or cast this as (MeshClass)
when creating the Anchor ?
I am not sure if one can use const_cast<MeshClass>(this)
to remove the constness of this
.
精彩评论