<< Operator overloading error in C++ -
i'm c++ beginner, trying learn online videos. in of operator overloading examples in lectures following code there , gives error
error: no match 'operator<<' in 'std::cout << operator+(((point&)(& p1)), ((point&)(& p2)))'compilation terminated due -wfatal-errors.
on line marked comment. can please tell what's wrong in code? trying professor explained in lecture can't compile.
===============
#include <iostream> using namespace std; class point{ public: double x,y; }; point operator+ (point& p1, point& p2) { point sum = {p1.x + p2.x, p1.y + p2.y}; return sum; } ostream& operator<< (ostream& out, point& p) { out << "("<<p.x<<","<<p.y<<")"; return out; } int main(int argc, const char * argv[]) { point p1 = {2,3}; point p2 = {2,3}; point p3; cout << p1 << p2; cout << p1+p2; // gives compliation error return 0; }
it's problem const correctness. operator+ returns temporary, can't bind non-const
reference when calling operator<<
. make signature:
ostream& operator<< (ostream& out, const point& p)
while don't need fix compilation error, won't able add const
points unless fix operator+
similarly:
point operator+(const point& p1, const point& p2)
Comments
Post a Comment