Implement operator<< overloading outside class
Oct 30, 2009 at 6:56pm UTC
Hi, I'm trying to overload the operator << for a class named "Point". The way I'm doing is this: I have three files, Point.cpp, Point.h and main.cpp.
Point.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
using namespace std;
class Point {
double x, y;
public :
Point(double x=0.0, double y=0.0): x(x), y(y) {};
friend ostream& operator << (ostream &o, Point p){
o << "(" << p.x << " " << p.y << ")" ;
return o;
}
};
main.cpp
1 2 3 4 5 6 7 8 9
#include "Point.h"
int main (){
Point p(1,2);
cout << p << endl;
}
and Point.cpp is currently empty. Then I try to move the operator<< code to Point.cpp, like this:
Point.cpp
1 2 3 4 5 6
#include "Point.h"
friend ostream& Point::operator << (ostream &o, Point p){
o << "(" << p.x << " " << p.y << ")" ;
return o;
}
And now I get the following error:
Point.cpp:3: error: ‘std::ostream& Point::operator<<(std::ostream&, Point)’ must take exactly one argument
Does anyone know how to handle this?
Thank you!
Last edited on Oct 30, 2009 at 7:11pm UTC
Oct 30, 2009 at 8:07pm UTC
Point::operator<< - the scope resolution operator :: says that operator<< is a member of the class, but friends are
not members. Remove the Point::.
Nov 3, 2009 at 9:57am UTC
Thank you jsmith!
With your help I managed to solve the problem. I also had to remove the keyword 'friend' when defining the method outside the class. The way I did is like this:
Point.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
using namespace std;
class Point {
double x, y;
public :
Point(double x=0.0, double y=0.0): x(x), y(y) {};
friend ostream& operator << (ostream &o, Point p);
};
Point.cpp
1 2 3 4 5 6
#include "Point.h"
ostream& operator << (ostream &o, Point p){
o << "(" << p.x << " " << p.y << ")" ;
return o;
}
Topic archived. No new replies allowed.