jeudi 26 juillet 2018

Best way to overload operator << in c++11

I am currently playing around with inheritance features using c++11, and would like to ask anyone who knows what is the best way to overload the operator << for the classes below.

Do I need to overload it once for each class? Or can I somehow use inheritance to only overload it once? What is the best way to do this?

#include <iostream>
#include <list>

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

    }
};

class Shape 
{ 

};

class Polygon : public Shape 
{
    public:
    std::list<Point> pList; // stores points

};

class Line : public Polygon 
{
    public:
    Line(){ 
        std::cout<<"Line contruction"<<std::endl;
    }
    Line(Point x, Point y){
        std::cout<<"Line contruction"<<std::endl;
        pList.push_back(x); // store point in list
        pList.push_back(y); // store point in list
    }

};

class Triangle : public Polygon 
{ 

};

class Circle : public Shape 
{ 

};

int main() 
{
    Line l1;                
    std::cout << l1;        

    Line l2(Point(), Point(100,100));   
    std::cout << l2; //e.g. Output: Line (0,0) (100,100)                 

    Triangle t1;            
    std::cout << t1;        

    Triangle t2(Point(-100,100), Point(100,100), Point(100,-100));  
    std::cout << t1;        

    Circle c1;              
    std::cout << c1;        

    return 0;           
}       

Aucun commentaire:

Enregistrer un commentaire