M.A
M.A

Reputation: 1133

Errors with operator overloading

i have two different operator overloading. For some reason it is giving error. If i remove one of it, than it does not show any error. May i know why ?

Can i combine both ?

This is used for printing on screen.

ostream& operator<<(ostream &out, const Point &p) {
return out << "[" << setw(4) << p.getX() << setw(1) << "," << setw(4) << p.getY() << "]   " << setprecision(3) << p.getScalarValue() << endl;
}

This is used for printing on a text file.

ofstream& operator<<(ofstream &out, const Point2D &p){
return out << "[" << setw(4) << p.getX() << setw(1) << "," << setw(4) << p.getY() << "]   " << setprecision(3) << p.getScalarValue() << endl;
}

Error:

Point.cpp:91:147: error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream&}’ from expression of type ‘std::basic_ostream::__ostream_type {aka std::basic_ostream}’

Upvotes: 0

Views: 90

Answers (1)

juanchopanza
juanchopanza

Reputation: 227608

You do not need the second version. You can use the first:

Point p;
std::ofstream pointsFile("points.txt");
pointsFile << p << "\n";

First, The std::ostream& operator<< works for writing to files as well as writing to the standard output or stderrt

Second, assuming Poind2D inherits from Point, passing a Point2D to a function or operator that takes a Point reference will work too.

Upvotes: 3

Related Questions