overloading operator<< for ofstream

This is the 1st program im trying to write somethink into .txt file but at 1 point operator<< overloading is not working. Why is that so?

1
2
3
4
5
6
7
  struct Point{
	double x = 0, 
	       y = 0;

	Point() = default;
	Point(double a, double b) : x{ a }, y{ b } {}
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
istream& operator>>(istream& is, Point& p){
	char ch1, ch2, ch3;
	double x, y;
	is >> ch1 >> x >> ch2 >> y >> ch3;
	if (!is) { 
		return is; }
	if (ch1 != '(' || ch2 != ',' || ch3 != ')'){
		is.clear(ios_base::failbit);
		return is;
	}
	
	p.x = x;
	p.y = y;
	return is;
}


1
2
3
ostream& operator<<(ostream& os, const Point& p){
	return os << "( " << p.x << " , " << p.y << " )";
}


1
2
3
4
5
6
ostream& operator<<(ostream& os, const vector<Point>& vec){
	for (Point p : vec){
		os << p << endl;
	}
	return os;
}


Very interesting but i actually did succeed with writing this vector<Point> into my .txt file but than i tryed to make operator<< work also just for a single Point just for completeness...
1
2
3
4
5
6
ofstream& operator<<(ofstream& ofs, const vector<Point>& vec){
	for (Point p : vec){
		ofs << p << endl;
	}
	return ofs;
}


... and this is the part thats not working!!!
1
2
3
ofstream& operator<<(ofstream& ofs, const Point& p){
	return ofs << "( " << p.x << " , " << p.y << " )";
}


Compiler gave me this error and i dont really understand it
Error 1 error C2440: 'return' : cannot convert from 'std::basic_ostream<char,std::char_traits<char>>' to 'std::ofstream &'
2
IntelliSense: a reference of type "std::ofstream &" (not const-qualified) cannot be initialized with a value of type "std::basic_ostream<char, std::char_traits<char>>"


I tested that i can use return ofs << p; but what if i wanted to add some chars somewhere around in case im writing this Point to file?
Last edited on
Why do you overload your function for ofstream&? There is no reason to do that.
Ops! I didnt notice that everything is actualy working using ostream& operator<< :) So yea tnx for good tip :) It saves typing.
Ill leave this as unsolved just coz would be interesting to see why it didnt work not coz i would really need to use this overloading

But yea, tnx a lot for answer :)
Operator << returns ostream& reference for all builtin types.

You are not supposed to require derived types unless you need to use some of additional functionality. This is the point of inheritance and dynamic dispatch.
Try this:
1
2
3
4
ofstream& operator<<(ofstream& ofs, const Point& p){
	ofs << "( " << p.x << " , " << p.y << " )";
	return ofs; // Note: the stream operator << returns ostream not ofstream
}
Thanks for answers guys :) I checked this version of code out and now its actually working so thats good to know. Now i can safety mark this as solved. Thank you guys a lot !!!
Topic archived. No new replies allowed.