Operator "<<" overloading return type
Suppose there is a cPoint class.
class cPoint {
int x, y, z;
};
I wanted to print all of three variables in a single statement. So, I overloaded operator << just like
friend std::ostream& operator<< (std::ostream &cout, cPoint &p);
std::ostream& operator<< (std::ostream &out, cPoint &p) {
out << p.get_x() << " " << p.get_y() << " " << p.get_z() << std::endl;
return out;
}
Make sense?
My question lies in the lines of that what would happen in case of insertion operator(>>). I overloaded that as well to take the values of x, y and z into a single statement.
friend std::istream& operator>> (std::istream &cin, Point &p);
std::istream& operator>> (std::istream &in, Point &p) {
int tmp;
in >> tmp;
p.set_x(tmp);
in >> tmp;
p.set_y(tmp);
in >> tmp;
p.set_z(tmp);
}
Clear?
int main() {
cout << p << endl;
cin >> p;
}
I know that if operator<< returned void then the compiler evaluates cout << p << endl; Due to the precedence/associativity rules, it evaluates this expression as (cout << cPoint) << endl;. cout << cPoint calls our void-returning overloaded operator<< function, which returns void. Then the partially evaluated expression becomes: void << endl;, which makes no sense!
But what would happen in case of >>. Why can't I return a void for >> as like:
void operator>> (std::istream &cin, Point &p);
Because it does not matter if cin >> p returns void or something else. There is no other operand who could use it. This is not clear.
You can return void
from stream extracting operator >>
, just like you can return void
from a stream inserting operator <<
. And just like with the inserting one, it will prevent you from doing chaining:
cPoint p, q;
cin >> p >> q; // This would fail with return type void
... and the very common test-correctness idiom:
cPoint p;
if (cin >> p) {
}
I overloaded operator <<
just like ...
Proper override should take the second parameter by const
reference:
friend std::ostream& operator<< (std::ostream &cout, const cPoint &p);
// ^^^^^
I overloaded that as well to take the values of x, y and z into a single statement.
You forgot to return in
from the implementation:
std::istream& operator>> (std::istream &in, Point &p) {
int tmp;
in >> tmp;
p.set_x(tmp);
in >> tmp;
p.set_y(tmp);
in >> tmp;
p.set_z(tmp);
return in; <<== Here
}
Making it void
would prevent you from reading anything else after the point on the same line.
上一篇: 递增和递减运算符重载
下一篇: 运算符“<<”重载返回类型