C ++,Printout(<<<<")运算符重载

时间:2015-09-24 13:33:03

标签: c++ operator-overloading

我是C ++的初学者,我正在尝试制作一个使用2个点的程序,将它们加在一起。然后将一条线与一条点一起添加,并获得一个多边形。

我正在尝试重载operator <<而不成功,以便我可以打印出我的行:

#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);        
}

编辑:

我现在可以cout OnePoint,但我不能cout Line

1 个答案:

答案 0 :(得分:1)

作为成员函数,运算符为this指针获取额外的隐藏参数。

您可以通过将其声明为类friend来使其成为自由函数:

class Line {
  // other members
public: 

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

};