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

Overloading ostream << on one class and output data of another class

本文关键字:lt 输出 数据 另一个 重载 一个 ostream      更新时间:2023-10-16
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> .

如果我只是试图通过重载<< operator来显示length,它可以完美地工作。但是当我尝试打印类::Point2D的xy时,我得到了错误。

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

操作符(正确地)使用const引用。因此,通过该引用调用的任何方法都必须是const。例如,

Point2D getPt1 () const;
                  ^^^^^

您还应该将Point2D类getter设置为const .