重载ostream<<在一个类和另一个类的输出数据

时间:2014-05-19 21:24:00

标签: c++ class overloading operator-keyword ostream

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;
}

当我运行这些代码时,我得到错误说:

no matching function for call to Line2D::getPt1() const

note: candidates are: Point2D Line2D::getPt1() <near match>

如果我只是试图通过重载length来显示<< operator,那么它的效果非常好。但是当我尝试打印Class :: Point2D的xy时,我收到错误。

那么打印xy的正确方法应该是什么?

1 个答案:

答案 0 :(得分:4)

您的运营商(正确)采用const参考。因此,通过该引用调用的任何方法都必须是const。例如,

Point2D getPt1 () const;
                  ^^^^^

您还应该使Point2D类getters const