Hello ladies and gents,
In my book, I'm currently reading about the use of creating your own operators << and >> for in- &output.
There's been given a small example that goes like this:
#include <iostream>
using namespace std;
class vec
{
public:
vec(float x1=0, float y1=0) {x = x1; y = y1;}
vec operator+(const vec &b) const
{
return vec(x + b.x, y + b.y);
}
float x, y;
};
ostream &operator<<(ostream &os, const vec &v)
{
return os << v.x << " " << v.y << endl;
}
istream &operator>>(istream &is, vec &v)
{
float x, y;
is >> x >> y;
v = vec(x, y);
return is;
}
int main()
{
vec u, v, s;
cout << "Typ twee getallenparen:\n";
cin >> u >> v;
s = u + v; // Vectoroptelling
cout << "De som bij vectoroptelling is:\n"
<< s;
return 0;
}
But, what is actually the benefit of writing it this way, when you could write it like this aswell?
#include <iostream>
using namespace std;
class vec
{
public:
vec(float x1=0, float y1=0) {x = x1; y = y1;}
void printvec() const
{
cout << x << " " << y << endl;
}
vec operator+(const vec &b) const
{
return vec(x + b.x, y + b.y);
}
private:
float x, y;
};
int main()
{
vec u(3, 1), v(1, 2), s;
s = u + v; // Vectoroptelling!
s.printvec(); // Uitvoer: 4 3
return 0;
}
Could someone explain what the actual benefit would be to use self defined << >> operators :?: