Reputation: 17454
class Point2D
{
protected:
int x;
int y;
public:
Point2D () {x=0; y=0;}
Point2D (int a, int b) {x=a; y=b;}
void setX (int);
void setY (int);
int getX ();
int getY ();
};
class Line2D
{
friend ostream& operator<< (ostream&, const Line2D&);
private:
Point2D pt1;
Point2D pt2;
double length;
public:
Line2D () {pt1 = Point2D(); pt2 = Point2D();}
Line2D (Point2D ptA, Point2D ptB) {pt1=ptA; pt2=ptB;}
void setPt1 (Point2D);
void setPt2 (Point2D);
Point2D getPt1 ();
Point2D getPt2 ();
};
ostream& operator<< (ostream &out, const Line2D &l)
{
//out << l.length << endl; //Reading length works perfectly
out << l.getPt1().getX() << endl; //But how to read x from pt1 ?
return out;
}
When I run these codes, I get error saying:
no matching function for call to Line2D::getPt1() const
and
note: candidates are: Point2D Line2D::getPt1() <near match>
.
If I am only trying to display length
by overloading << operator
, it works perfectly. But when I try to printx
and y
of Class::Point2D, I get error.
So what should be the proper way to print out x
and y
?
Upvotes: 0
Views: 105
Reputation: 227418
Your operator (rightly) takes a const
reference. So any methods called via that reference must be const
. For example,
Point2D getPt1 () const;
^^^^^
You should also make the Point2D
class getters const
.
Upvotes: 4