-
operator <<
I am trying to make a point class for school, and I get this error: "Error E2080 Point.h 20: 'Point::operator <<(ostream &,const Point &)' must be declared with one parameter". I have no idea what to do, as I had code that worked before like this with the apmatrix class. This is my code (all the relevant parts):
Code:
//Point.h
#include <iostream>
using namespace std;
class Point
{
public:
ostream& operator <<(ostream&, const Point&);
private:
int m_x;
int m_y;
};
//Point.cpp
ostream& Point::operator <<(ostream& os, const Point& p)
{
os << "(" << p.m_x << "," << p.m_y << ")";
return *this; //?
}
-
Despite my limited C++ knowledge, I'm trying to help you, since operator overloading is actually basic knowledge.
Try this:
Code:
//Point.h
#include <iostream>
using namespace std;
class Point
{
public:
friend ostream& operator <<(ostream&, const Point&);
private:
int m_x;
int m_y;
};
//Point.cpp
ostream& operator <<(ostream& os, const Point& p)
{
return os << "(" << p.m_x << "," << p.m_y << ")";
}
Modifications and explanations:
1) Add the "friend" keyword to the operator<< declaration in your class. The operator<< function needs to access class members.
2) I've removed the Point:: part from the operator, since it's an operator, and not really a part of the class itself. Because of function overloading the <<-operator knows that it should use your function.
3) The result of the operator<< function is a stream. You can return this stream immediately.
os << "(" << p.m_x << "," << p.m_y << ")"; does nothing by itself. The resulting stream object of it is stored nowhere.
Good luck!
-