【问题标题】:Overloading ostream << on one class and output data of another class在一个类上重载 ostream << 并输出另一类的数据
【发布时间】: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() &lt;near match&gt;.

如果我只是试图通过重载 &lt;&lt; operator 来显示 length ,它就可以完美地工作。但是当我尝试打印 Class::Point2D 的xy 时,出现错误。

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

【问题讨论】:

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


    【解决方案1】:

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

    Point2D getPt1 () const;
                      ^^^^^
    

    您还应该使 Point2D 类吸气剂 const

    【讨论】:

    • 我应该在function declarationfunction definition header 上添加const 吗?如果你觉得这个问题太简单了,我很抱歉..
    • +1 它正在工作。您的回复快速而准确。我希望我能为你 +20.. :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2013-05-18
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2022-08-04
    • 2021-06-29
    相关资源
    最近更新 更多