confusion on a const function that is calling a non-const function
Basically there are three classes I defined: paralelogram
, point
and line
classes, and paralelogram
has some vector
s of point
s and line
s, and in the paralelogram
class I am defining a compute_area
function as
double Paralelogram::compute_area() const
{
assert( !points.empty() );
double h = points[3].distance_to_line( lines[0] ); // point[3] is the last point in
// the vector however it is not a
// const object, and this gives a
// compile time error
double base = points[0].distance_to_point( points[1] );
return base*h;
}
Edit distance_to_line
function is non-const
double Point::distance_to_line(Line& l)
{
return l.distance_to_point(*this);
}
deleting the const
from the function definition and declaration solves the problem, however my reasoning, while coding, was compute_area
does not modify the object so it can be const
, however this is right as long as it operates on const
objects and calls functions of const
objects, right?
If the point
objects are not const
also, this is not valid anymore. And since they are not const
that is the reason why it works after the const
removal.
This is a puzzling point for me where I do not modify the object however the objects it uses gives the problem and moreover what I am thinking I am still not changing those objects as well, but apparently there is a confusio开发者_如何转开发n in my const
understanding. One more thing, is this somehow related to the this
pointer of the Paralelogram
class if yes can you clarify?
In a const function, types of every member becomes const in such a way that you cannot modify them (unless they're declared mutable
), nor can you call any non-const function using them.
It seems that in your code, distance_to_line
is non-const function, but you're calling it from a const
function, that means inside const function points[3]
and points[0]
becomes const object, so you cannot call non-const function (which I believe distance_to_line
is) on const object.
--
EDIT:
You need to make distance_to_line
a const function, and since this function calls distance_to_point
, you've to make even distance_to_point
const function.
To make a member function const, you don't need to make the member variables const as well. You just need to ensure that your const function does not modify any of the member variables of the class.
Have you tried making the distance_to_line()
function const on the point class? If that works, you'll also probably need to make distance_to_point()
const as well. If these aren't const, the compiler can't ensure that the calling function is also const.
Make distance_to_line()
and distance_to_point()
const and your error will go away.
By declaring the function const
, you're also restricting your access to any members - they'll be treated as if they were const
as well. Since you can't call a non-const member function on a const object, those calls will fail.
精彩评论