I have this snippet of code here. The intention is to make a copy of initialData. Since I am not modifying initialData in any way, I figure that I should pass it as a const reference. However, I keep getting this message when compiling.
.\src\Scene\SceneAnimationData.cpp(23) : error C2662: 'SceneTrackerData::getRect' : cannot convert 'this' pointer from 'const SceneTrackerData' to 'SceneTrackerData &'
#include "SceneTrackerData.h"
void SceneAnimationData::SetupData(const SceneTrackerData &initialData)
{
// getRect(), points() and links() all return const pointers
CloneRect(initialData.getRect());
ClonePoints(initialData.points()->values());
CloneLinks(initialData.links()->values());
}
void SceneAnimationData::CloneRect(const QGraphicsRectItem * initialRect)
{
if (initialRect != NULL)
{
QPointF position = initialRect->scenePos();
QRectF rect = initialRect->rect();
initialRect = new QGraphicsRectItem(rect);
initialRect->setPos(position);
}
}
void SceneAnimationData::CloneLinks(const QList<QGraphicsLineItem*> links)
{
links_ = new QList<QGraphicsLineItem*>(*links);
}
void SceneAnimationData::ClonePoints(const QList<QGraphicsEllipseItem*> points)
{
points_ = new QList<QGraphicsEllipseItem*>(*points);
}
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.
Then, no, you can't do that; in a const method you have a const this pointer (in your case it would be a const Foo * ), which means that any reference you can get to its fields1 will be a const reference, since you're accessing them through a " const path".
When you pass by const reference, you take the argument in by reference (avoiding making any copies of it), but cannot make any changes to the original object (much as would happen when you would take the parameters in by value).
const member functions Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.
Without the definition of SceneTrackerData
, it's hard to say, but likely that function (SceneTrackerData::getRect
) is not marked as const.
That is, what is (guessing):
const Rect& SceneTrackerData::getRect(void)
Should be:
const Rect& SceneTrackerData::getRect(void) const
// ^
// |
// does not logically modify the object
It's not clear which is line 23 here; but my guess is that you are calling methods on the object that are not themselves declared as const
and thus are not usable by a const
object reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With