What's wrong with this segment of code?
class Point2d {
public:
Point2d(float x = 0.0, float y = 0.0)
: _x(x), _y(y) {};
float x() { return _x; }
float y() { return _y; }
void x(float newX) { _x = newX; }
void y(float newY) { _y = newY; }
void Point2d::operator += ( const Point2d & rhs) {
_x += rhs.x();
_y += rhs.y();
}
protected:
float _x, _y;
};
If I eliminate the keyword const, it will be ok.
But why?
i think you should declare the methods x() and y() as const, so the compiler knows they are not changing any contents of the class:
class Point2d {public:Point2d(float x = 0.0, float y = 0.0): _x(x), _y(y) {};float x() const { return _x; }float y() const { return _y; }void x(float newX) { _x = newX; }void y(float newY) { _y = newY; }void Point2d::operator += ( const Point2d & rhs) {_x += rhs.x();_y += rhs.y();}protected:float _x, _y;};
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement