【发布时间】:2014-05-19 21:23:59
【问题描述】:
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;
}
当我运行这些代码时,我得到 error 说:
no matching function for call to Line2D::getPt1() const 和
note: candidates are: Point2D Line2D::getPt1() <near match>.
如果我只是试图通过重载 << operator 来显示 length ,它就可以完美地工作。但是当我尝试打印 Class::Point2D 的x 和 y 时,出现错误。
那么打印出x 和y 的正确方法应该是什么?
【问题讨论】:
标签: c++ class overloading operator-keyword ostream