In ostream &operator, i just use one param (because another is own this pointer). But I got error (i comment on code).
When I use two params, i still got error
I know exacctly why ? Because this function is member of class. If i put it outside class, no error. Why ? Does IO overloading only support for global function ?
can you explain in more detail why it should be a friend and not a member, I thought that using << on a Vector2d was exactly what we wanted to achieve by overloading operator<<
Yes, I agree with quirkyusername (47) . Galik (1309) : I know why does it cause error ? But you can explain why ? Why other operators support overloading inside class, but IO operator doesn't. And I have other questions, why in this function, before operator have operator &.
When you make operator << a class member, it makes objects of that class receive the output like this:
1 2 3
Vector2D v1, v2;
v1 << v2;
If you want a different class of object to receive the output you have to define the function outside of any specific class. That way you get to specify the types of both sides of the expression:
class A
{
};
class B
{
};
A& operator<<(A& a, const B& b); // this allows a << b;
class C
{
public:
C& operator<<(A& a); // this allows (*this) << a;
C& operator<<(B& a); // this allows (*this) << b;
};
// if I want to make C about to output to A (a << c) I need to either add a
// member function to A or make a non-class function
A& operator<<(A& a, const C& c); // this allows a << c;
// if I want to make C about to output to ostream (cout << c) I need to either add a
// member function to ostream (not possible) or make a non-class function
ostream& operator<<(ostream& os, const C& c); // this allows cout << c;
In this context (as a parameter qualifier) it means a reference. Parameters are normally copied when passed to a function and the function operates on the copies. But if you qualify them with an & then they are not copied and the function operates on the original.