0

I am a beginner at C++ and I am trying to make a program that uses 2 points, adds them together to a line. Then adds a line together with a point, and gets a polygon.

I am trying, unsuccessfully, to overload the operator << so that I can print out my line:

#include <iostream>
using namespace std;

class Line {
private: 
    OnePoint onevalue; 
    OnePoint twovalue; 
public: 
    Line(OnePoint a, OnePoint b) {
        onevalue = a; 
        twovalue = b; 
    }

ostream& operator<<(ostream& print, Line& linje){ // Error right here. 
    print << linje.onevalue << ',' << linje.twovalue; // Too many 
    return print; // parameters for this type of function
}    
};

class OnePoint {
private: 
    double xvalue; 
    double yvalue; 
public:
    OnePoint(double x = 0.0, double y = 0.0) {
    xvalue = x;
    yvalue = y;
}

friend ostream& operator<<(ostream& printh, OnePoint& cPoint) {
     printh << "(" << cPoint.xvalue << ',' << cPoint.yvalue << ")";
     return printh;
}

void Plus(OnePoint a) {
    xvalue = xvalue + a.xvalue; 
    yvalue = yvalue + a.yvalue; 
}

void Minus(OnePoint b) {     
    xvalue = xvalue + b.xvalue;
    yvalue = yvalue + b.yvalue;
}

OnePoint Plustwo(OnePoint a) {
     return (xvalue + a.xvalue, yvalue - a.yvalue); 
}

void Change(double a, double b) {
      xvalue += a;
      yvalue += b; 
}

void Print(OnePoint b) {
      cout << xvalue << "," << yvalue << endl; 
}

OnePoint operator+(OnePoint a) {
       OnePoint temp; 
       temp.xvalue = xvalue + a.xvalue; 
       temp.yvalue = yvalue + a.yvalue; 
       return temp; 
}        
};

//--------------------------------------------------------------------        
int main(){  
    OnePoint a(3.0, 3.0); 
    OnePoint b(1.0, 1.0);  
    OnePoint d(1.0, 4.0);
    OnePoint c; 

    c = a + b + d;         
    c.Print(c);        
}

Edit:

I can now cout my OnePoint, but I cannot cout Line.

Ziezi
  • 6,187
  • 3
  • 36
  • 46
David Lund
  • 235
  • 1
  • 6

1 Answers1

1

As a member function, the operator gets an extra hidden parameter for the this pointer.

You can make it a free function by declaring it a friend of the class:

class Line {
  // other members
public: 

  friend ostream& operator<<(ostream& print, Line& linje){
    print << linje.onevalue << ',' << linje.twovalue; 
    return print;             
  }

};
Bo Persson
  • 88,437
  • 31
  • 141
  • 199