jeudi 26 juillet 2018

Printing out an object in c++ (Operator overloading)

I need some help overloading my operator << for the situation below. A line object is constructed using point objects, and I would like to know how I can overload the operator << so that I can print out the points used to construct the line.

The points are stored in a list for printing. Sample output is in the comments below

Any help is appreciated. Thanks!

class Point{
    int x_;
    int y_;
    public:
    Point(int x = 0, int y = 0)
    :x_{x}, y_{y}
    {

    }
};

class Line
{
    std::list<Point> pList;
    public:
    Line(){ 
        std::cout<<"Line contruction"<<std::endl;
    }

    Line(Point x, Point y){
        std::cout<<"Line contruction"<<std::endl;
        pList.push_back(x);
        pList.push_back(y);
    }

    friend std::ostream& operator<<(std::ostream&stream, const Line& line);
};

std::ostream& operator<<(std::ostream&stream, const Line& line){
  // insert code here
}
int main() 
{
    Line l2(Point(), Point(100,100)); //Output:Line construction
    std::cout << l2;                  //Output:Line(0,0),(100,100)
}

Aucun commentaire:

Enregistrer un commentaire